<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;

return new class extends Migration
{
    private const TENANT_CODE = 'desfile_pura_tendencia';

    private const CATALOG_SLUG = 'entrada';

    public function up(): void
    {
        $variantIds = $this->variantIds();

        if ($variantIds->isEmpty()) {
            return;
        }

        DB::transaction(function () use ($variantIds): void {
            DB::table('variant_event_dates')
                ->whereIn('variant_id', $variantIds)
                ->delete();

            DB::table('variantes')
                ->whereIn('id', $variantIds)
                ->update(['event_date_id' => null]);
        });
    }

    public function down(): void
    {
        $eventDateId = DB::table('event_dates')
            ->where('tenant_code', self::TENANT_CODE)
            ->where('date', '2026-10-16')
            ->value('id');
        $variantIds = $this->variantIds();

        if ($eventDateId === null || $variantIds->isEmpty()) {
            return;
        }

        DB::transaction(function () use ($eventDateId, $variantIds): void {
            DB::table('variantes')
                ->whereIn('id', $variantIds)
                ->update(['event_date_id' => $eventDateId]);

            foreach ($variantIds as $variantId) {
                DB::table('variant_event_dates')->insertOrIgnore([
                    'variant_id' => $variantId,
                    'event_date_id' => $eventDateId,
                ]);
            }
        });
    }

    private function variantIds(): Collection
    {
        return DB::table('variantes')
            ->join('catalog_items', 'catalog_items.id', '=', 'variantes.catalog_item_id')
            ->where('catalog_items.tenant_code', self::TENANT_CODE)
            ->where('catalog_items.slug', self::CATALOG_SLUG)
            ->pluck('variantes.id');
    }
};
