<?php

namespace App\Policies;

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

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

    public function viewAny(User $user): bool
    {
        return $user->can(PermissionName::COLLATERAL_VIEW->value);
    }

    public function view(User $user, Collateral $collateral): bool
    {
        return $user->can(PermissionName::COLLATERAL_VIEW->value)
            && $this->canAccess($user, $collateral);
    }

    public function create(User $user): bool
    {
        return $user->can(PermissionName::COLLATERAL_MANAGE->value);
    }

    public function update(User $user, Collateral $collateral): bool
    {
        return $user->can(PermissionName::COLLATERAL_MANAGE->value)
            && $this->canAccess($user, $collateral);
    }

    public function move(User $user, Collateral $collateral): bool
    {
        return $user->can(PermissionName::COLLATERAL_CUSTODY->value)
            && $this->canAccess($user, $collateral);
    }

    public function manageDocuments(User $user, Collateral $collateral): bool
    {
        return $user->can(PermissionName::COLLATERAL_DOCUMENTS->value)
            && $this->canAccess($user, $collateral);
    }

    public function manageCategories(User $user): bool
    {
        return $user->can(PermissionName::COLLATERAL_MANAGE->value);
    }

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