<?php

namespace App\Services\Meet;

use App\Models\Message;
use App\Models\Reaction;
use App\Models\Session;

class ChatService
{
    public function sendPublicMessage(
        Session $session,
        string $senderName,
        string $body,
        ?string $senderRef = null,
    ): Message {
        return Message::create([
            'owner_ref' => $session->owner_ref,
            'session_id' => $session->id,
            'sender_ref' => $senderRef,
            'sender_name' => $senderName,
            'type' => 'public',
            'body' => $body,
        ]);
    }

    public function sendReaction(
        Session $session,
        string $senderName,
        string $emoji,
        ?string $participantRef = null,
    ): Reaction {
        return Reaction::create([
            'owner_ref' => $session->owner_ref,
            'session_id' => $session->id,
            'participant_ref' => $participantRef,
            'sender_name' => $senderName,
            'emoji' => $emoji,
        ]);
    }

    /**
     * @return \Illuminate\Database\Eloquent\Collection<int, Message>
     */
    public function recentMessages(Session $session, int $limit = 100)
    {
        return $session->messages()
            ->where('type', 'public')
            ->orderByDesc('created_at')
            ->limit($limit)
            ->get()
            ->reverse()
            ->values();
    }
}
