<?php

namespace App\Policies;

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

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

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

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

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

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

    public function update(User $user, WebForm $form): bool
    {
        $decision = AccessControl::overridePermissionState($user, 'forms', 'update');
        if ($decision !== null) {
            return $decision;
        }

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

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

    public function delete(User $user, WebForm $form): bool
    {
        $decision = AccessControl::overridePermissionState($user, 'forms', 'delete');
        if ($decision !== null) {
            return $decision;
        }

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

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