<?php

namespace App\Policies;

use App\Models\HrRequest;
use App\Models\User;
use App\Support\AccessControl;

class HrRequestPolicy
{
    public function viewAny(User $user): bool
    {
        return AccessControl::allows($user, 'hr', 'read');
    }

    public function view(User $user, HrRequest $hrRequest): bool
    {
        $decision = AccessControl::overridePermissionState($user, 'hr', 'read');
        if ($decision !== null) {
            return $decision;
        }

        if (! AccessControl::roleAllows($user, 'hr', 'read')) {
            return false;
        }

        if (AccessControl::isElevated($user)) {
            return true;
        }

        return in_array($user->id, [
            (int) ($hrRequest->employee_user_id ?? 0),
            (int) ($hrRequest->assignee_user_id ?? 0),
            (int) ($hrRequest->creator_user_id ?? 0),
        ], true);
    }

    public function create(User $user): bool
    {
        return AccessControl::allows($user, 'hr', 'create');
    }

    public function update(User $user, HrRequest $hrRequest): bool
    {
        $decision = AccessControl::overridePermissionState($user, 'hr', 'update');
        if ($decision !== null) {
            return $decision;
        }

        if (! AccessControl::roleAllows($user, 'hr', 'update')) {
            return false;
        }

        if (AccessControl::isElevated($user)) {
            return true;
        }

        return in_array($user->id, [
            (int) ($hrRequest->assignee_user_id ?? 0),
            (int) ($hrRequest->creator_user_id ?? 0),
        ], true);
    }

    public function delete(User $user, HrRequest $hrRequest): bool
    {
        $decision = AccessControl::overridePermissionState($user, 'hr', 'delete');
        if ($decision !== null) {
            return $decision;
        }

        if (! AccessControl::roleAllows($user, 'hr', 'delete')) {
            return false;
        }

        if (AccessControl::isElevated($user)) {
            return true;
        }

        return (int) ($hrRequest->creator_user_id ?? 0) === (int) $user->id;
    }
}
