<?php

namespace App\Policies;

use App\Models\Project;
use App\Models\User;
use App\Support\AccessControl;

class ProjectPolicy
{
    public function viewAny(User $user): bool
    {
        return AccessControl::allows($user, 'projects', 'read');
    }

    public function view(User $user, Project $project): bool
    {
        $decision = AccessControl::overridePermissionState($user, 'projects', 'read');
        if ($decision !== null) {
            return $decision;
        }

        if (!AccessControl::roleAllows($user, 'projects', 'read')) {
            return false;
        }

        return AccessControl::isElevated($user)
            || $project->owner_id === $user->id
            || $project->manager_id === $user->id
            || $project->members()->where('users.id', $user->id)->exists();
    }

    public function create(User $user): bool
    {
        return AccessControl::allows($user, 'projects', 'create');
    }

    public function update(User $user, Project $project): bool
    {
        $decision = AccessControl::overridePermissionState($user, 'projects', 'update');
        if ($decision !== null) {
            return $decision;
        }

        if (!AccessControl::roleAllows($user, 'projects', 'update')) {
            return false;
        }

        return AccessControl::isElevated($user)
            || $project->owner_id === $user->id
            || $project->manager_id === $user->id;
    }

    public function delete(User $user, Project $project): bool
    {
        $decision = AccessControl::overridePermissionState($user, 'projects', 'delete');
        if ($decision !== null) {
            return $decision;
        }

        if (!AccessControl::roleAllows($user, 'projects', 'delete')) {
            return false;
        }

        return AccessControl::isElevated($user);
    }

    public function manageTasks(User $user, Project $project): bool
    {
        $decision = AccessControl::overridePermissionState($user, 'projects', 'update');
        if ($decision !== null) {
            return $decision;
        }

        if (!AccessControl::roleAllows($user, 'projects', 'update')) {
            return false;
        }

        return $this->update($user, $project)
            || $project->members()->where('users.id', $user->id)->exists();
    }
}
