<?php

namespace App\Policies;

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

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

    public function view(User $user, Contact $contact): bool
    {
        return AccessControl::allows($user, 'contacts', 'read');
    }

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

    public function update(User $user, Contact $contact): bool
    {
        $decision = AccessControl::overridePermissionState($user, 'contacts', 'update');
        if ($decision !== null) {
            return $decision;
        }

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

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

    public function delete(User $user, Contact $contact): bool
    {
        $decision = AccessControl::overridePermissionState($user, 'contacts', 'delete');
        if ($decision !== null) {
            return $decision;
        }

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

        return AccessControl::isElevated($user);
    }
}
