<?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
{
    public function up(): void
    {
        Schema::create('clients', function (Blueprint $table): void {
            $table->id();
            $table->string('code')->unique();
            $table->string('name');
            $table->timestamps();
        });

        Schema::table('tenants', function (Blueprint $table): void {
            $table->foreignId('client_id')->nullable()->after('id')->constrained('clients')->restrictOnDelete();
        });

        DB::table('tenants')
            ->select(['id', 'codigo', 'nombre', 'created_at', 'updated_at'])
            ->orderBy('id')
            ->each(function (object $tenant): void {
                $clientId = DB::table('clients')->insertGetId([
                    'code' => $tenant->codigo,
                    'name' => $tenant->nombre,
                    'created_at' => $tenant->created_at ?? now(),
                    'updated_at' => $tenant->updated_at ?? now(),
                ]);

                DB::table('tenants')->where('id', $tenant->id)->update(['client_id' => $clientId]);
            });

        Schema::table('tenants', function (Blueprint $table): void {
            $table->unsignedBigInteger('client_id')->nullable(false)->change();
        });
    }

    public function down(): void
    {
        Schema::table('tenants', function (Blueprint $table): void {
            $table->dropConstrainedForeignId('client_id');
        });

        Schema::dropIfExists('clients');
    }
};
