<?php

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

return new class extends Migration
{
    public function up(): void
    {
        if (!Schema::hasTable('in_accounts')) {
            return;
        }

        Schema::table('in_accounts', function (Blueprint $table) {
            if (!Schema::hasColumn('in_accounts', 'user_id')) {
                $table->unsignedBigInteger('user_id')->nullable();
            }

            if (!Schema::hasColumn('in_accounts', 'username')) {
                $table->string('username', 30)->nullable();
            }

            if (!Schema::hasColumn('in_accounts', 'password')) {
                $table->string('password')->nullable();
            }

            if (!Schema::hasColumn('in_accounts', 'temp_email')) {
                $table->string('temp_email')->nullable();
            }

            if (!Schema::hasColumn('in_accounts', 'two_fa_code')) {
                $table->string('two_fa_code')->nullable();
            }

            if (!Schema::hasColumn('in_accounts', 'status')) {
                $table->string('status')->default('pending');
            }
        });

        if (Schema::hasColumn('in_accounts', 'user_id') && !Schema::hasIndex('in_accounts', ['user_id'], 'index')) {
            Schema::table('in_accounts', function (Blueprint $table) {
                $table->index('user_id');
            });
        }

        if (Schema::hasColumn('in_accounts', 'username') && !Schema::hasIndex('in_accounts', ['username'], 'unique')) {
            Schema::table('in_accounts', function (Blueprint $table) {
                $table->unique('username');
            });
        }

        if (Schema::hasColumn('in_accounts', 'status') && !Schema::hasIndex('in_accounts', ['status'], 'index')) {
            Schema::table('in_accounts', function (Blueprint $table) {
                $table->index('status');
            });
        }
    }

    public function down(): void
    {
        // Intentionally left as-is to avoid destructive rollback on live data.
    }
};
