<?php

namespace App\Policies\Messenger;

use App\Models\User;
use App\Models\Messenger\Message;
use App\Models\Messenger\Conversation;

class MessagePolicy
{
    public function view(User $user, Message $message): bool
    {
        return $message->conversation->isParticipant($user->id);
    }

    public function create(User $user, Conversation $conversation): bool
    {
        return $conversation->isParticipant($user->id);
    }

    public function update(User $user, Message $message): bool
    {
        // Only the message author can edit
        if ($message->user_id !== $user->id) {
            return false;
        }

        // Can't edit system messages
        if ($message->isSystemMessage()) {
            return false;
        }

        // Can't edit deleted messages
        if ($message->is_deleted) {
            return false;
        }

        // Can only edit text messages
        if ($message->type !== 'text') {
            return false;
        }

        // Can only edit within a reasonable time window (e.g., 1 hour)
        $editWindow = setting('message_edit_window_minutes', 60);
        if ($message->created_at->diffInMinutes(now()) > $editWindow) {
            return false;
        }

        return true;
    }

    public function delete(User $user, Message $message): bool
    {
        // Message author can always delete their own messages
        if ($message->user_id === $user->id) {
            return true;
        }

        // Admins can delete messages in group conversations
        if ($message->conversation->isGroup()) {
            $participant = $message->conversation->getParticipant($user->id);
            return $participant && $participant->isAdmin();
        }

        return false;
    }

    public function markAsRead(User $user, Message $message): bool
    {
        // Can't mark your own messages as read
        if ($message->user_id === $user->id) {
            return false;
        }

        return $message->conversation->isParticipant($user->id);
    }
}
