<?php

namespace App\Policies;

use App\Models\LoanWriteOff;
use App\Models\User;
use App\Services\BranchAccessService;
use App\Support\Authorization\PermissionName;

class LoanWriteOffPolicy
{
    public function __construct(private BranchAccessService $branchAccess)
    {
    }

    public function view(User $user, LoanWriteOff $writeOff): bool
    {
        return $user->can(PermissionName::LOANS_WRITEOFF_VIEW->value)
            && $this->canAccess($user, $writeOff);
    }

    public function decide(User $user, LoanWriteOff $writeOff): bool
    {
        return $user->can(PermissionName::LOANS_WRITEOFF_APPROVE->value)
            && $this->canAccess($user, $writeOff);
    }

    public function recover(User $user, LoanWriteOff $writeOff): bool
    {
        return $user->can(PermissionName::LOANS_WRITEOFF_RECOVER->value)
            && $this->canAccess($user, $writeOff);
    }

    public function downloadDocument(User $user, LoanWriteOff $writeOff): bool
    {
        return $this->view($user, $writeOff);
    }

    private function canAccess(User $user, LoanWriteOff $writeOff): bool
    {
        return $this->branchAccess->canAccessBranch($user, (int) $writeOff->branch_id);
    }
}
