<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Str;

return new class extends Migration
{
    public function up(): void
    {
        if (! Schema::hasColumn('menues', 'label')) {
            Schema::table('menues', function (Blueprint $table) {
                $table->string('label')->nullable()->after('code');
            });
        }

        $labels = [
            'index' => 'Inicio',
            'product.detail' => 'Detalle de producto',
            'checkout' => 'Finalizar compra',
            'account' => 'Mi cuenta',
            'account.profile' => 'Datos personales',
            'account.purchases' => 'Mis compras',
            'account.tickets' => 'Mis tickets',
            'help' => 'Ayuda',
            'help.faq' => 'Preguntas frecuentes',
            'help.contact' => 'Contacto',
            'help.payment-methods' => 'Medios de pago',
            'help.shipping' => 'Envíos',
            'help.terms-and-conditions' => 'Términos y condiciones',
        ];

        DB::table('menues')
            ->select(['id', 'code'])
            ->orderBy('id')
            ->eachById(function ($menu) use ($labels): void {
                $fallback = Str::headline(Str::afterLast($menu->code, '.'));

                DB::table('menues')
                    ->where('id', $menu->id)
                    ->update(['label' => $labels[$menu->code] ?? $fallback]);
            });

        Schema::table('menues', function (Blueprint $table) {
            $table->string('label')->nullable(false)->change();
        });
    }

    public function down(): void
    {
        Schema::table('menues', function (Blueprint $table) {
            $table->dropColumn('label');
        });
    }
};
