<?php

namespace App\Policies;

use App\Models\Conversation;
use App\Models\ConversationParticipant;
use App\Models\User;

class ConversationPolicy
{
    public function view(User $user, Conversation $conversation): bool
    {
        return $this->participantRecord($user, $conversation) !== null
            && (bool) ($conversation->is_active ?? true);
    }

    public function send(User $user, Conversation $conversation): bool
    {
        return $this->view($user, $conversation);
    }

    public function manageParticipants(User $user, Conversation $conversation): bool
    {
        $participant = $this->participantRecord($user, $conversation);

        return $participant !== null && $participant->role === 'admin';
    }

    public function rename(User $user, Conversation $conversation): bool
    {
        return $conversation->isGroup() && $this->manageParticipants($user, $conversation);
    }

    public function joinPresence(User $user, Conversation $conversation): bool
    {
        return $this->view($user, $conversation);
    }

    private function participantRecord(User $user, Conversation $conversation): ?ConversationParticipant
    {
        return ConversationParticipant::query()
            ->where('conversation_id', $conversation->id)
            ->where('user_id', $user->id)
            ->whereNull('left_at')
            ->first();
    }
}
