<?php

namespace App\Modules\HR\Overtime\Policies;

use App\Models\User;
use App\Modules\HR\Overtime\Models\OvertimeRequest;
use App\Modules\HR\Overtime\Support\OvertimeRequestStatus;

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

    public function view(User $user, OvertimeRequest $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('overtime.view');
    }

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

        return ! $user->is_admin
            && $user->tenant_id !== null
            && $user->employee_id !== null;
    }

    public function review(User $user, OvertimeRequest $request): bool
    {
        return $request->status === OvertimeRequestStatus::PENDING
            && $user->can('overtime.review');
    }

    public function cancel(User $user, OvertimeRequest $request): bool
    {
        if ($request->status !== OvertimeRequestStatus::PENDING) {
            return false;
        }
        if ((int) $user->tenant_id !== (int) $request->tenant_id) {
            return false;
        }
        if ($user->can('overtime.create') || $user->can('overtime.review')) {
            return true;
        }

        return $user->employee_id !== null
            && (int) $user->employee_id === (int) $request->employee_id;
    }
}
