<?php

namespace App\Policies;

use App\Models\MessengerMessage;
use App\Models\MessengerSetting;
use App\Models\User;
use App\Support\AccessControl;
use App\Support\MessengerAccess;

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

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

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

        $conversationUserId = $message->conversation?->user_id;

        if (AccessControl::isElevated($user) || ($conversationUserId !== null && $conversationUserId === $user->id)) {
            return true;
        }

        if ($conversationUserId === null) {
            $settings = MessengerSetting::query()->first();

            return MessengerAccess::canAcceptIncoming($user, $settings);
        }

        return false;
    }

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

    public function update(User $user, MessengerMessage $message): bool
    {
        $decision = AccessControl::overridePermissionState($user, 'messengers', 'update');
        if ($decision !== null) {
            return $decision;
        }

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

        $conversationUserId = $message->conversation?->user_id;

        if (AccessControl::isElevated($user) || ($conversationUserId !== null && $conversationUserId === $user->id)) {
            return true;
        }

        if ($conversationUserId === null) {
            $settings = MessengerSetting::query()->first();

            return MessengerAccess::canAcceptIncoming($user, $settings);
        }

        return false;
    }

    public function delete(User $user, MessengerMessage $message): bool
    {
        $decision = AccessControl::overridePermissionState($user, 'messengers', 'delete');
        if ($decision !== null) {
            return $decision;
        }

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

        $conversationUserId = $message->conversation?->user_id;

        if (AccessControl::isElevated($user) || ($conversationUserId !== null && $conversationUserId === $user->id)) {
            return true;
        }

        if ($conversationUserId === null) {
            $settings = MessengerSetting::query()->first();

            return MessengerAccess::canAcceptIncoming($user, $settings);
        }

        return false;
    }
}
