<?php

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

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

    public function up(): void
    {
        $this->replaceSeatOptions(100);
    }

    public function down(): void
    {
        $this->replaceSeatOptions(17);
    }

    private function replaceSeatOptions(int $maximum): void
    {
        $attributeId = DB::table('attribute')
            ->where('tenant_codigo', self::TENANT_CODE)
            ->where('codigo', 'asiento')
            ->value('id');

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

        DB::transaction(function () use ($attributeId, $maximum): void {
            DB::table('attribute_options')->where('attribute_id', $attributeId)->delete();

            $now = now();
            DB::table('attribute_options')->insert(array_map(
                fn (int $seat): array => [
                    'attribute_id' => $attributeId,
                    'validity_time_id' => null,
                    'value' => (string) $seat,
                    'label' => (string) $seat,
                    'sort_order' => $seat,
                    'metadata' => null,
                    'created_at' => $now,
                    'updated_at' => $now,
                ],
                range(1, $maximum),
            ));
        });
    }
};
