<?php

declare(strict_types=1);

namespace ImovelZapAi\Publishing\Connectors\GroupOlx\Application\Services;

use ImovelZapAi\Publishing\Connectors\GroupOlx\Application\Ports\GroupOlxPublicationLogWriterInterface;
use ImovelZapAi\Publishing\Connectors\GroupOlx\Infrastructure\Persistence\Eloquent\GroupOlxPublicationLogModel;
use ImovelZapAi\Publishing\Domain\Feeds\VrSync\ListingDataFeed;

/**
 * PublicationLogs do feed VRSync — append-only.
 */
final class GroupOlxPublicationLogger implements GroupOlxPublicationLogWriterInterface
{
    /**
     * @param  list<string>  $errors
     * @param  list<string>  $warnings
     */
    public function record(
        string $tenantId,
        int $listingCount,
        int $durationMs,
        bool $success,
        array $errors = [],
        array $warnings = [],
        ?int $triggeredBy = null,
        ?string $contentHash = null,
        ?string $version = null,
    ): GroupOlxPublicationLogModel {
        /** @var GroupOlxPublicationLogModel $log */
        $log = GroupOlxPublicationLogModel::query()->create([
            'tenant_id' => $tenantId,
            'triggered_by' => $triggeredBy,
            'listing_count' => $listingCount,
            'duration_ms' => max(0, $durationMs),
            'success' => $success,
            'version' => $version ?? ListingDataFeed::VERSION,
            'content_hash' => $contentHash,
            'errors' => $errors === [] ? null : array_values($errors),
            'warnings' => $warnings === [] ? null : array_values($warnings),
            'generated_at' => now(),
        ]);

        return $log;
    }
}
