<?php

namespace App\Policies\Concerns;

use App\Models\User;
use Illuminate\Database\Eloquent\Model;

/**
 * Shared behaviour for policies guarding branch-owned models:
 *  - Super Admin bypasses every check.
 *  - Otherwise an ability requires the matching permission AND that the model
 *    lives in a branch the user can access.
 */
trait HandlesBranchPolicy
{
    public function before(User $user, string $ability): ?bool
    {
        return $user->isSuperAdmin() ? true : null;
    }

    protected function allows(User $user, string $permission, ?Model $model = null): bool
    {
        if (! $user->can($permission)) {
            return false;
        }

        if ($model && isset($model->branch_id)) {
            return $user->canAccessBranch((int) $model->branch_id);
        }

        return true;
    }
}
