<?php

namespace App\Policies;

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

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

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

    public function view(User $user, Customer $customer): bool
    {
        return $user->can(PermissionName::CUSTOMERS_VIEW->value)
            && $this->canAccess($user, $customer);
    }

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

    public function update(User $user, Customer $customer): bool
    {
        return $user->can(PermissionName::CUSTOMERS_UPDATE->value)
            && $this->canAccess($user, $customer);
    }

    public function manageDocuments(User $user, Customer $customer): bool
    {
        return $user->can(PermissionName::CUSTOMERS_DOCUMENTS->value)
            && $this->canAccess($user, $customer);
    }

    public function manageGuarantors(User $user, Customer $customer): bool
    {
        return $user->can(PermissionName::CUSTOMERS_GUARANTORS->value)
            && $this->canAccess($user, $customer);
    }

    public function manageWatchlist(User $user, Customer $customer): bool
    {
        return $user->can(PermissionName::CUSTOMERS_WATCHLIST->value)
            && $this->canAccess($user, $customer);
    }

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