<?php

namespace App\Policies;

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

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

    public function view(User $user, Task $task): bool
    {
        return $user->can(PermissionName::TASKS_VIEW->value)
            && $this->branchAccess->canAccessBranch($user, (int) $task->branch_id);
    }

    public function update(User $user, Task $task): bool
    {
        return $user->can(PermissionName::TASKS_UPDATE->value)
            && $this->branchAccess->canAccessBranch($user, (int) $task->branch_id);
    }

    public function updateStatus(User $user, Task $task): bool
    {
        if (! $user->can(PermissionName::TASKS_UPDATE_STATUS->value)
            || ! $this->branchAccess->canAccessBranch($user, (int) $task->branch_id)) {
            return false;
        }

        return (int) $task->assigned_to === (int) $user->id
            || $user->can(PermissionName::TASKS_ASSIGN->value);
    }
}
