<?php

declare(strict_types=1);

namespace App\Policies;

use App\Enums\UserRole;
use App\Models\MemberTransfer;
use App\Models\User;
use App\Policies\Concerns\ChecksBranchAccess;

class TransferPolicy
{
    use ChecksBranchAccess;

    public function viewAny(User $user): bool
    {
        return true;
    }

    /**
     * Requesting a transfer needs write access to the member's current branch.
     */
    public function create(User $user, int $fromBranchId): bool
    {
        return $user->role !== UserRole::Viewer && $this->canAccessBranch($user, $fromBranchId);
    }

    /**
     * Approving requires write access (branch_admin+) to the destination branch.
     */
    public function approve(User $user, MemberTransfer $transfer): bool
    {
        return in_array($user->role, [UserRole::SuperAdmin, UserRole::RegionAdmin, UserRole::BranchAdmin], true)
            && $this->canAccessBranch($user, $transfer->to_branch_id);
    }

    public function reject(User $user, MemberTransfer $transfer): bool
    {
        return $this->approve($user, $transfer);
    }

    /**
     * Cancelling requires being the original requester, or an admin over the source branch.
     */
    public function cancel(User $user, MemberTransfer $transfer): bool
    {
        if ($user->id === $transfer->requested_by) {
            return true;
        }

        return in_array($user->role, [UserRole::SuperAdmin, UserRole::RegionAdmin, UserRole::BranchAdmin], true)
            && $this->canAccessBranch($user, $transfer->from_branch_id);
    }
}
