<?php

namespace App\Policies;

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

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

    public function acknowledge(User $user, ManagementAlert $alert): bool
    {
        return $user->can(PermissionName::MANAGEMENT_ALERTS_ACKNOWLEDGE->value)
            && $this->canAccessAlert($user, $alert);
    }

    public function resolve(User $user, ManagementAlert $alert): bool
    {
        return $user->can(PermissionName::MANAGEMENT_ALERTS_RESOLVE->value)
            && $this->canAccessAlert($user, $alert);
    }

    private function canAccessAlert(User $user, ManagementAlert $alert): bool
    {
        if ($this->branchAccess->isSystemWide($user)) {
            return true;
        }

        return $alert->branch_id !== null
            && $this->branchAccess->canAccessBranch($user, (int) $alert->branch_id);
    }
}
