<?php

namespace Modules\Approval\Policies;

use App\Models\User;
use Illuminate\Auth\Access\HandlesAuthorization;
use Modules\Approval\Enums\ApprovalRequestStatusEnum;
use Modules\Approval\Enums\ApprovalStepStatusEnum;
use Modules\Approval\Models\ApprovalRequest;

class ApprovalRequestPolicy
{
    use HandlesAuthorization;

    /**
     * Create a new policy instance.
     */
    public function audit(User $user): bool
    {
        return $user->can('approval.request.audit');
    }
    
    public function viewAny(User $authUser): bool
    {
        return $authUser->can('approval.request.view');
    }

    public function view(User $authUser, ApprovalRequest $request): bool
    {
        return $authUser->can('approval.request.view');
    }

    public function approve(User $authUser, ApprovalRequest $request): bool
    {
        if ($request->status !== ApprovalRequestStatusEnum::PENDING->value) {
            return false;
        }

        $step = $request->currentStep;

        if (!$step) {
            return false;
        }

        if ($step->status !== ApprovalStepStatusEnum::PENDING->value) {
            return false;
        }

        if (!$authUser->can($step->permission_name)) {
            return false;
        }

        return $authUser->roles()->whereKey($step->workflowStep->role_id)->exists();
    }

    public function approve0(User $authUser, ApprovalRequest $request): bool
    {
        if ($request->status !== ApprovalRequestStatusEnum::PENDING->value) {
            return false;
        }

        $step = $request->currentStep;

        if (!$step) {
            return false;
        }

        if ($step->status !== ApprovalStepStatusEnum::PENDING->value) {
            return false;
        }

        return $authUser->can($step->permission_name);
    }

    public function reject(User $authUser, ApprovalRequest $request): bool
    {
        return $this->approve($authUser, $request);
    }
}
