<?php

namespace App\Modules\HR\Leave\Policies;

use App\Models\User;
use App\Modules\HR\Leave\Models\LeaveRequest;
use App\Modules\HR\Leave\Support\LeaveRequestStatus;

class LeaveRequestPolicy
{
    public function viewAny(User $user): bool
    {
        return $user->can('leave.view');
    }

    public function view(User $user, LeaveRequest $request): bool
    {
        if ((int) $user->tenant_id !== (int) $request->tenant_id) {
            return false;
        }
        if ($user->employee_id !== null && (int) $user->employee_id === (int) $request->employee_id) {
            return true;
        }

        return $user->can('leave.view', $request);
    }

    public function create(User $user): bool
    {
        if ($user->can('leave.create')) {
            return true;
        }

        // Self-service: linked employees submit only for themselves (employee_id enforced in /me controllers).
        return ! $user->is_admin
            && $user->tenant_id !== null
            && $user->employee_id !== null;
    }

    public function approveManager(User $user, LeaveRequest $request): bool
    {
        return $request->status === LeaveRequestStatus::PENDING
            && $user->can('leave.approve.manager', $request);
    }

    public function approveHr(User $user, LeaveRequest $request): bool
    {
        return $request->status === LeaveRequestStatus::MANAGER_APPROVED
            && $user->can('leave.approve.hr', $request);
    }

    public function reject(User $user, LeaveRequest $request): bool
    {
        if (! in_array($request->status, [
            LeaveRequestStatus::PENDING,
            LeaveRequestStatus::MANAGER_APPROVED,
            LeaveRequestStatus::HR_APPROVED,
        ], true)) {
            return false;
        }

        return $user->can('leave.reject', $request);
    }

    public function cancel(User $user, LeaveRequest $request): bool
    {
        if ((int) $user->tenant_id !== (int) $request->tenant_id) {
            return false;
        }
        if (! in_array($request->status, [
            LeaveRequestStatus::PENDING,
            LeaveRequestStatus::MANAGER_APPROVED,
        ], true)) {
            return false;
        }
        if ($user->employee_id !== null && (int) $user->employee_id === (int) $request->employee_id) {
            return true;
        }

        return $user->can('leave.create') || $user->can('leave.reject');
    }
}
