<?php

declare(strict_types=1);

namespace App\Policies;

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

class MemberPolicy
{
    use ChecksBranchAccess;

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

    public function view(User $user, Member $member): bool
    {
        return $this->canAccessBranch($user, $member->branch_id);
    }

    public function create(User $user, ?int $branchId = null): bool
    {
        return $user->role !== UserRole::Viewer && $this->canAccessBranch($user, $branchId);
    }

    public function update(User $user, Member $member): bool
    {
        return $user->role !== UserRole::Viewer && $this->canAccessBranch($user, $member->branch_id);
    }

    public function delete(User $user, Member $member): bool
    {
        return in_array($user->role, [UserRole::SuperAdmin, UserRole::RegionAdmin, UserRole::BranchAdmin], true)
            && $this->canAccessBranch($user, $member->branch_id);
    }

    public function changeStatus(User $user, Member $member): bool
    {
        return $user->role !== UserRole::Viewer && $this->canAccessBranch($user, $member->branch_id);
    }

    /**
     * Moving a member OUT of deceased requires branch_admin+.
     */
    public function changeStatusFromDeceased(User $user, Member $member): bool
    {
        return in_array($user->role, [UserRole::SuperAdmin, UserRole::RegionAdmin, UserRole::BranchAdmin], true)
            && $this->canAccessBranch($user, $member->branch_id);
    }
}
