<?php

declare(strict_types=1);

namespace ImovelZapAi\Importing\Application\Queries;

use ImovelZapAi\Importing\Infrastructure\Persistence\Eloquent\ImportErrorModel;
use ImovelZapAi\Importing\Infrastructure\Persistence\Eloquent\ImportJobModel;
use ImovelZapAi\Importing\Infrastructure\Persistence\Eloquent\ImportLogModel;

final class GetImportReportQuery
{
    /**
     * @return array<string, mixed>
     */
    public function execute(ImportJobModel $job): array
    {
        $issues = ImportErrorModel::query()
            ->where('import_job_id', $job->id)
            ->orderBy('listing_index')
            ->get()
            ->map(static fn (ImportErrorModel $error): array => [
                'id' => $error->id,
                'severity' => $error->severity->value ?? (string) $error->severity,
                'code' => $error->code,
                'external_id' => $error->external_id,
                'listing_index' => $error->listing_index,
                'path' => $error->path,
                'message' => $error->message,
                'status' => $error->status,
                'resolution' => $error->resolution,
            ])
            ->all();

        $itemResults = ImportLogModel::query()
            ->where('import_job_id', $job->id)
            ->whereNotNull('listing_index')
            ->orderBy('listing_index')
            ->get()
            ->map(static fn (ImportLogModel $log): array => [
                'listing_index' => $log->listing_index,
                'external_id' => $log->external_id,
                'property_id' => $log->property_id,
                'event' => $log->event->value ?? (string) $log->event,
                'result' => $log->result,
                'message' => $log->message,
                'photos_count' => $log->photos_count,
                'duration_ms' => $log->duration_ms,
            ])
            ->all();

        return [
            'id' => $job->id,
            'status' => $job->status->value ?? (string) $job->status,
            'summary' => $job->report_summary ?? [
                'imported' => $job->imported_count,
                'updated' => $job->updated_count,
                'unchanged' => $job->unchanged_count,
                'ignored' => $job->ignored_count,
                'failed' => $job->failed_count,
                'photos_imported' => $job->photos_imported,
            ],
            'issues' => $issues,
            'items' => $itemResults,
            'completed_at' => $job->completed_at?->toIso8601String(),
        ];
    }
}
