<?php

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
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        // For SQLite, we must recreate the table to change CHECK constraints
        Schema::create('clientes_new', function (Blueprint $table) {
            $table->id();
            $table->foreignId('tenant_id')->constrained()->onDelete('cascade');
            $table->string('nombre');
            $table->string('telefono')->nullable();
            $table->string('email')->nullable();
            $table->string('tipo_identificacion')->comment('R=RUC, C=Cedula, E=Exterior/Pasaporte');
            $table->string('razon_social')->nullable();
            $table->string('ruc')->nullable();
            $table->string('ciudad')->nullable();
            $table->string('direccion')->nullable();
            $table->timestamps();

            $table->index(['tenant_id', 'ruc']);
        });

        // Copy and map data
        DB::statement("INSERT INTO clientes_new (id, tenant_id, nombre, telefono, email, tipo_identificacion, razon_social, ruc, ciudad, direccion, created_at, updated_at)
            SELECT id, tenant_id, nombre, telefono, email, 
                CASE 
                    WHEN tipo_identificacion = 'E' THEN 'R'
                    WHEN tipo_identificacion = 'P' THEN 'C'
                    WHEN tipo_identificacion = 'X' THEN 'E'
                    ELSE 'C'
                END, 
                razon_social, ruc, ciudad, direccion, created_at, updated_at 
            FROM clientes");

        Schema::disableForeignKeyConstraints();
        Schema::drop('clientes');
        Schema::rename('clientes_new', 'clientes');
        Schema::enableForeignKeyConstraints();
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        // Reverse mapping not strictly needed for dev, but let's be safe
        Schema::table('clientes', function (Blueprint $table) {
            $table->enum('tipo_identificacion', ['E', 'P', 'X'])->comment('E=Empresa, P=Persona natural, X=Exterior')->change();
        });
    }
};
