<?php

declare(strict_types=1);

namespace ImovelZapAi\Owners\Application\Queries;

use ImovelZapAi\Owners\Application\Services\DefaultListingPipelineSeeder;
use ImovelZapAi\Owners\Infrastructure\Persistence\Eloquent\ListingOpportunityModel;

final class GetListingKanbanQuery
{
    public function __construct(
        private readonly DefaultListingPipelineSeeder $pipelineSeeder,
    ) {}

    /**
     * @return array{pipeline_id: string, columns: list<array<string, mixed>>}
     */
    public function execute(string $tenantId): array
    {
        $pipeline = $this->pipelineSeeder->ensureForTenant($tenantId);
        $grouped = ListingOpportunityModel::query()
            ->where('tenant_id', $tenantId)
            ->where('pipeline_id', $pipeline->id)
            ->with(['owner', 'property', 'responsible', 'stage'])
            ->orderByDesc('last_activity_at')
            ->limit(500)
            ->get()
            ->groupBy('stage_id');

        $columns = [];
        foreach ($pipeline->stages as $stage) {
            $cards = ($grouped->get($stage->id) ?? collect())->map(fn (ListingOpportunityModel $opp) => [
                'id' => $opp->id,
                'title' => $opp->title,
                'owner' => $opp->owner?->name,
                'property' => $opp->property?->title,
                'asking' => $opp->owner_asking_price,
                'recommended' => $opp->agency_recommended_price,
                'responsible' => $opp->responsible?->name,
                'stalled_hours' => $opp->stage_entered_at
                    ? (int) $opp->stage_entered_at->diffInHours(now())
                    : null,
            ])->values()->all();

            $columns[] = [
                'stage_id' => $stage->id,
                'key' => $stage->key instanceof \BackedEnum ? $stage->key->value : $stage->key,
                'name' => $stage->name,
                'color' => $stage->color,
                'cards' => $cards,
            ];
        }

        return ['pipeline_id' => $pipeline->id, 'columns' => $columns];
    }
}
