<?php

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

return new class extends Migration
{
    public function up(): void
    {
        $now = now();

        DB::table('tenants')
            ->whereExists(fn ($query) => $query
                ->selectRaw('1')
                ->from('event_dates')
                ->whereColumn('event_dates.tenant_code', 'tenants.codigo'))
            ->orderBy('id')
            ->each(function (object $tenant) use ($now): void {
                DB::table('attribute')->updateOrInsert(
                    [
                        'tenant_codigo' => $tenant->codigo,
                        'codigo' => 'event_date',
                    ],
                    [
                        'nombre' => 'Fecha',
                        'is_required' => true,
                        'metadata_schema' => null,
                        'type' => 'event_date',
                        'updated_at' => $now,
                        'created_at' => $now,
                    ],
                );
            });

        DB::table('catalog_items')
            ->whereExists(fn ($query) => $query
                ->selectRaw('1')
                ->from('variantes')
                ->whereColumn('variantes.catalog_item_id', 'catalog_items.id')
                ->whereNotNull('variantes.event_date_id'))
            ->orderBy('id')
            ->each(function (object $catalogItem) use ($now): void {
                $attributeId = DB::table('attribute')
                    ->where('tenant_codigo', $catalogItem->tenant_code)
                    ->where('codigo', 'event_date')
                    ->value('id');

                if ($attributeId === null) {
                    return;
                }

                DB::table('item_attributes')->updateOrInsert(
                    [
                        'catalog_item_id' => $catalogItem->id,
                        'attribute_id' => $attributeId,
                    ],
                    [
                        'updated_at' => $now,
                        'created_at' => $now,
                    ],
                );
            });
    }

    public function down(): void
    {
        $attributeIds = DB::table('attribute')
            ->where('codigo', 'event_date')
            ->where('type', 'event_date')
            ->pluck('id');

        DB::table('item_attributes')->whereIn('attribute_id', $attributeIds)->delete();
        DB::table('attribute')->whereIn('id', $attributeIds)->delete();
    }
};
