<?php

declare(strict_types=1);

namespace App\Repositories;

use App\Contracts\Repositories\MessageRepositoryInterface;
use App\Models\Message;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;

final class EloquentMessageRepository implements MessageRepositoryInterface
{
    /**
     * Find message by ID
     */
    public function findById(int $id): ?Message
    {
        return Message::with(['conversation', 'sender'])->find($id);
    }

    /**
     * Create a new message
     *
     * @param  array<string, mixed>  $data
     */
    public function create(array $data): Message
    {
        return Message::create($data);
    }

    /**
     * Get paginated messages for a conversation
     */
    public function getForConversation(int $conversationId, int $perPage = 50): LengthAwarePaginator
    {
        return Message::with('sender')
            ->where('conversation_id', $conversationId)
            ->orderBy('created_at', 'asc')
            ->paginate($perPage);
    }

    /**
     * Mark all unread messages in a conversation as read for a specific recipient
     */
    public function markConversationAsRead(int $conversationId, int $recipientId): int
    {
        return Message::where('conversation_id', $conversationId)
            ->where('sender_id', '!=', $recipientId)
            ->whereNull('read_at')
            ->update(['read_at' => now()]);
    }

    /**
     * Get the latest message for a conversation
     */
    public function getLatestMessage(int $conversationId): ?Message
    {
        return Message::where('conversation_id', $conversationId)
            ->latest('created_at')
            ->first();
    }
}
