<?php

namespace App\Services\Messaging;

use App\Models\Conversation;
use App\Models\Message;
use App\Models\User;
use Illuminate\Support\Collection;

class ConversationDeltaService
{
    public function __construct(
        private readonly MessagingPayloadFactory $payloadFactory,
    ) {}

    public function messagesAfter(Conversation $conversation, User $viewer, int $afterMessageId, ?int $limit = null): Collection
    {
        $maxMessages = max(1, (int) config('messaging.recovery.max_messages', 100));
        $effectiveLimit = min($limit ?? $maxMessages, $maxMessages);

        return Message::withTrashed()
            ->where('conversation_id', $conversation->id)
            ->where('id', '>', $afterMessageId)
            ->with(['sender:id,username,name', 'reactions', 'attachments'])
            ->orderBy('id')
            ->limit($effectiveLimit)
            ->get()
            ->map(fn (Message $message) => $this->payloadFactory->message($message, (int) $viewer->id))
            ->values();
    }
}
