<?php

declare(strict_types=1);

namespace ImovelZapAi\Conversations\Application\Queries;

use Illuminate\Support\Collection;
use ImovelZapAi\Conversations\Application\Data\BrokerNoteData;
use ImovelZapAi\Conversations\Infrastructure\Persistence\Eloquent\BrokerNoteModel;

final class BrokerNotesQuery
{
    /**
     * @return Collection<int, BrokerNoteData>
     */
    public function forContact(string $tenantId, string $contactId, ?string $conversationId = null): Collection
    {
        $query = BrokerNoteModel::query()
            ->where('tenant_id', $tenantId)
            ->where('contact_id', $contactId)
            ->with('author')
            ->orderByDesc('created_at');

        if ($conversationId !== null) {
            $query->where(function ($builder) use ($conversationId): void {
                $builder->whereNull('conversation_id')
                    ->orWhere('conversation_id', $conversationId);
            });
        }

        return $query
            ->get()
            ->map(fn (BrokerNoteModel $note): BrokerNoteData => new BrokerNoteData(
                id: (string) $note->id,
                body: (string) $note->body,
                authorName: trim((string) ($note->author?->name ?? 'Corretor')),
                createdAt: $note->created_at ?? now(),
            ));
    }
}
