<?php

declare(strict_types=1);

namespace ImovelZapAi\Sales\Application\Queries;

use ImovelZapAi\Sales\Application\Services\DefaultPipelineSeeder;
use ImovelZapAi\Sales\Infrastructure\Persistence\Eloquent\DealModel;

final class GetDealKanbanQuery
{
    public function __construct(
        private readonly DefaultPipelineSeeder $pipelineSeeder,
    ) {}

    /**
     * @return array{pipeline_id: string, columns: list<array<string, mixed>>}
     */
    public function execute(string $tenantId): array
    {
        $pipeline = $this->pipelineSeeder->ensureForTenant($tenantId);
        $stages = $pipeline->stages;

        $deals = DealModel::query()
            ->where('tenant_id', $tenantId)
            ->where('pipeline_id', $pipeline->id)
            ->with(['contact', 'property', 'responsible', 'stage'])
            ->orderByDesc('last_activity_at')
            ->limit(500)
            ->get()
            ->groupBy('stage_id');

        $columns = [];
        foreach ($stages as $stage) {
            $cards = ($deals->get($stage->id) ?? collect())->map(function (DealModel $deal) use ($stage) {
                $stalledHours = $deal->stage_entered_at
                    ? (int) $deal->stage_entered_at->diffInHours(now())
                    : null;

                return [
                    'id' => $deal->id,
                    'title' => $deal->title,
                    'contact' => $deal->contact?->display_name,
                    'property' => $deal->property?->title,
                    'amount' => $deal->amount,
                    'responsible' => $deal->responsible?->name,
                    'stage' => $stage->name,
                    'priority' => $deal->priority->value ?? $deal->priority,
                    'next_action_at' => $deal->next_action_at?->toIso8601String(),
                    'next_action_type' => $deal->next_action_type->value ?? $deal->next_action_type,
                    'stalled_hours' => $stalledHours,
                ];
            })->values()->all();

            $columns[] = [
                'stage_id' => $stage->id,
                'key' => $stage->key,
                'name' => $stage->name,
                'color' => $stage->color,
                'is_won' => $stage->is_won,
                'is_lost' => $stage->is_lost,
                'cards' => $cards,
            ];
        }

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