<?php

namespace Database\Seeders;

use App\Domains\Catalog\Enums\FeaturedGroupSource;
use App\Domains\Catalog\Enums\GroupLayout;
use App\Domains\Catalog\Enums\InventoryPolicy;
use App\Domains\Catalog\Enums\ProductLayout;
use App\Domains\Catalog\Models\CatalogItem;
use App\Domains\Catalog\Models\Category;
use App\Domains\Catalog\Models\FeaturedGroup;
use App\Domains\Catalog\Services\CatalogService;
use App\Domains\Event\Models\EventDate;
use App\Domains\Tenant\Models\Tenant;
use App\Domains\Ticket\Enums\ValidityTimeType;
use App\Domains\Ticket\Models\ValidityTime;
use Illuminate\Database\Seeder;
use RuntimeException;

class FiestaFutbolInfantilProductSeeder extends Seeder
{
    public function __construct(private readonly CatalogService $catalogService) {}

    public function run(): void
    {
        $tenant = Tenant::query()->where('codigo', 'fiesta_futbol_infantil')->first();

        if (! $tenant) {
            throw new RuntimeException("Tenant 'fiesta_futbol_infantil' no encontrado.");
        }

        $this->deleteExistingCatalog($tenant);
        FeaturedGroup::query()->where('tenant_code', $tenant->codigo)->delete();
        Category::query()->where('tenant_code', $tenant->codigo)->update(['categoria_id' => null]);
        Category::query()->where('tenant_code', $tenant->codigo)->delete();

        $categories = collect([
            'entradas' => 'Entradas',
            'alojamientos' => 'Alojamientos',
            'comidas' => 'Comidas',
            'merchandising' => 'Merchandising',
        ])->map(fn (string $name): Category => Category::query()->create([
            'nombre' => $name,
            'tenant_code' => $tenant->codigo,
        ]));

        $tenant->update([
            'event_title' => 'Fiesta Nacional del Fútbol Infantil',
            'event_location' => 'Sunchales, Santa Fe',
        ]);

        $existingValidityTimeIds = $tenant->eventDates()->pluck('validity_time_id');
        $tenant->eventDates()->delete();
        ValidityTime::query()->whereKey($existingValidityTimeIds)->delete();

        $eventDates = collect(['2026-10-09', '2026-10-10', '2026-10-11', '2026-10-12'])
            ->map(function (string $date) use ($tenant): EventDate {
                $validityTime = ValidityTime::query()->create([
                    'type' => ValidityTimeType::FixedWindow,
                    'start_time' => null,
                    'end_time' => null,
                    'fixed_starts_at' => $date.' 00:00:00',
                    'fixed_expires_at' => $date.' 23:59:59',
                ]);

                $eventDate = new EventDate;
                $eventDate->forceFill([
                    'date' => $date,
                    'time_start' => '00:00:00',
                    'time_end' => '23:59:59',
                    'validity_time_id' => $validityTime->id,
                ]);

                return $tenant->eventDates()->save($eventDate);
            });
        $dateIds = $eventDates->pluck('id')->map(fn ($id): int => (int) $id)->values();

        $this->createProduct($tenant, [
            'slug' => 'camiseta',
            'nombre' => 'Camiseta',
            'group_order' => 1,
            'category_id' => $categories['merchandising']->id,
            'precio' => 18000,
            'attribute_codes' => ['color', 'talle'],
            'variants' => collect(['Verde', 'Blanco'])
                ->crossJoin(['14', 'S', 'M', 'L', 'XL', 'XXL'])
                ->map(fn (array $values, int $index): array => [
                    'real_stock' => [24, 3, 18, 0, 12, 2, 25, 0, 14, 1, 19, 8][$index],
                    'values' => ['color' => $values[0], 'talle' => $values[1]],
                ])->all(),
        ]);

        $this->createProduct($tenant, [
            'slug' => 'alojamiento',
            'nombre' => 'Alojamiento',
            'group_order' => 2,
            'category_id' => $categories['alojamientos']->id,
            'precio' => 35000,
            'attribute_codes' => ['tipo_alojamiento'],
            'variants' => collect(['Carpa', 'Motorhome'])->map(fn (string $type, int $index): array => [
                'real_stock' => [0, 3][$index],
                'values' => ['tipo_alojamiento' => $type],
            ])->all(),
        ]);

        $this->createProduct($tenant, [
            'slug' => 'comida',
            'nombre' => 'Comida',
            'group_order' => 4,
            'category_id' => $categories['comidas']->id,
            'precio' => 4000,
            'attribute_codes' => ['event_date', 'horario', 'servicio'],
            'variants' => $eventDates
                ->crossJoin(['Desayuno', 'Almuerzo', 'Cena'], ['Comedor', 'Vianda'])
                ->map(fn (array $values, int $index): array => [
                    'real_stock' => [80, 3, 65, 0, 42, 2, 70, 18, 0, 5, 55, 40, 90, 1, 35, 0, 60, 8, 75, 22, 0, 4, 50, 30][$index],
                    'event_date_ids' => [(int) $values[0]->id],
                    'descripcion' => sprintf(
                        '%s del %s - %s',
                        $values[1],
                        $values[0]->date->format('d/m/Y'),
                        $values[2],
                    ),
                    'precio' => $this->foodPrice($values[1]),
                    'values' => ['horario' => $values[1], 'servicio' => $values[2]],
                ])->all(),
        ]);

        $this->createProduct($tenant, [
            'slug' => 'abono',
            'nombre' => 'Abono',
            'group_order' => 3,
            'category_id' => $categories['entradas']->id,
            'precio' => 40000,
            'has_tickets' => true,
            'attribute_codes' => ['event_date'],
            'multi_select_attribute_codes' => ['event_date'],
            'hidden_attribute_codes' => ['event_date'],
            'variants' => [[
                'real_stock' => 120,
                'event_date_ids' => $dateIds->all(),
            ]],
        ]);

        FeaturedGroup::query()->create([
            'tenant_code' => $tenant->codigo,
            'code' => 'productos',
            'source_type' => FeaturedGroupSource::All,
            'category_id' => null,
            'product_layout' => ProductLayout::Row,
            'group_layout' => GroupLayout::SimpleVertical,
            'group_name' => 'Productos',
            'group_order' => 0,
        ]);
    }

    private function deleteExistingCatalog(Tenant $tenant): void
    {
        CatalogItem::query()
            ->where('tenant_code', $tenant->codigo)
            ->orderByRaw("CASE WHEN type = 'bundle' THEN 0 ELSE 1 END")
            ->orderBy('id')
            ->each(fn (CatalogItem $item) => $this->catalogService->delete($item));
    }

    /** @param array<string, mixed> $data */
    private function createProduct(Tenant $tenant, array $data): CatalogItem
    {
        return $this->catalogService->create([
            'tenant_code' => $tenant->codigo,
            'descripcion' => $data['nombre'],
            'inventory_policy' => InventoryPolicy::Tracked->value,
            ...$data,
            'has_tickets' => true,
        ]);
    }

    private function foodPrice(string $schedule): int
    {
        return match ($schedule) {
            'Desayuno' => 4000,
            'Almuerzo' => 10000,
            'Cena' => 8000,
            default => throw new RuntimeException("Horario de comida desconocido: {$schedule}"),
        };
    }
}
