<?php

use App\Enums\OrderType;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        if (! Schema::hasTable('tbl_order_types')) {
            Schema::create('tbl_order_types', function (Blueprint $table) {
                $table->increments('id_order_type');
                $table->string('code', 50)->unique();
                $table->string('name', 120);
                $table->boolean('is_active')->default(true);
                $table->timestamps();
            });
        }

        Schema::table('tbl_order_types', function (Blueprint $table) {
            if (! Schema::hasColumn('tbl_order_types', 'id_order_type')) {
                $table->increments('id_order_type');
            }
            if (! Schema::hasColumn('tbl_order_types', 'code')) {
                $table->string('code', 50)->unique();
            }
            if (! Schema::hasColumn('tbl_order_types', 'name')) {
                $table->string('name', 120);
            }
            if (! Schema::hasColumn('tbl_order_types', 'is_active')) {
                $table->boolean('is_active')->default(true);
            }
            if (! Schema::hasColumn('tbl_order_types', 'created_at')) {
                $table->timestamps();
            }
        });

        foreach (OrderType::cases() as $case) {
            DB::table('tbl_order_types')->updateOrInsert(
                ['code' => $case->value],
                [
                    'name' => $case->label(),
                    'is_active' => true,
                    'updated_at' => now(),
                    'created_at' => now(),
                ]
            );
        }
    }

    public function down(): void
    {
        // No hacemos drop para evitar pérdida de datos.
    }
};
