<?php

namespace App\Policies;

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

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

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

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

        return AccessControl::isElevated($user) || $mailbox->user_id === $user->id;
    }

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

    public function update(User $user, Mailbox $mailbox): bool
    {
        $decision = AccessControl::overridePermissionState($user, 'mail', 'update');
        if ($decision !== null) {
            return $decision;
        }

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

        return AccessControl::isElevated($user) || $mailbox->user_id === $user->id;
    }

    public function delete(User $user, Mailbox $mailbox): bool
    {
        $decision = AccessControl::overridePermissionState($user, 'mail', 'delete');
        if ($decision !== null) {
            return $decision;
        }

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

        return AccessControl::isElevated($user) || $mailbox->user_id === $user->id;
    }
}

