<?php

declare(strict_types=1);

namespace ImovelZapAi\Sales\Application\Services;

use ImovelZapAi\Sales\Domain\Enums\DealStageKey;
use ImovelZapAi\Sales\Infrastructure\Persistence\Eloquent\SalesDealStageModel;
use ImovelZapAi\Sales\Infrastructure\Persistence\Eloquent\SalesPipelineModel;

final class DefaultPipelineSeeder
{
    public function ensureForTenant(string $tenantId): SalesPipelineModel
    {
        $pipeline = SalesPipelineModel::query()
            ->where('tenant_id', $tenantId)
            ->where('is_default', true)
            ->first();

        if ($pipeline !== null) {
            return $pipeline->load('stages');
        }

        $pipeline = SalesPipelineModel::query()->create([
            'tenant_id' => $tenantId,
            'name' => 'Pipeline padrão',
            'is_default' => true,
        ]);

        foreach (DealStageKey::defaultPipelineDefinition() as $stage) {
            SalesDealStageModel::query()->create([
                'tenant_id' => $tenantId,
                'pipeline_id' => $pipeline->id,
                'key' => $stage['key'],
                'name' => $stage['name'],
                'position' => $stage['position'],
                'is_won' => $stage['is_won'],
                'is_lost' => $stage['is_lost'],
                'color' => $stage['color'],
            ]);
        }

        return $pipeline->load('stages');
    }

    public function stageByKey(string $tenantId, string $key, ?string $pipelineId = null): SalesDealStageModel
    {
        $pipeline = $pipelineId !== null
            ? SalesPipelineModel::query()->where('tenant_id', $tenantId)->whereKey($pipelineId)->firstOrFail()
            : $this->ensureForTenant($tenantId);

        $stage = SalesDealStageModel::query()
            ->where('pipeline_id', $pipeline->id)
            ->where('key', $key)
            ->first();

        if ($stage === null) {
            throw \ImovelZapAi\Sales\Domain\Exceptions\DealException::stageNotFound($key);
        }

        return $stage;
    }
}
