<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('bank_accounts', function (Blueprint $table) {
            // Check if column doesn't exist before adding
            if (!Schema::hasColumn('bank_accounts', 'company_id')) {
                // Add company_id as nullable first (to handle existing records)
                $table->foreignId('company_id')
                    ->nullable()
                    ->after('id')
                    ->constrained('companies')
                    ->onDelete('cascade');

                // Add index for better performance when filtering by company
                $table->index(['company_id', 'is_active']);
            }
        });

        // Update existing bank accounts with company_id from their banks
        DB::statement('
            UPDATE bank_accounts ba
            INNER JOIN banks b ON ba.bank_id = b.id
            SET ba.company_id = b.company_id
            WHERE ba.company_id IS NULL AND b.company_id IS NOT NULL
        ');

        // For bank accounts whose banks don't have company_id, set to default company (1)
        DB::statement('
            UPDATE bank_accounts ba
            SET ba.company_id = 1
            WHERE ba.company_id IS NULL
        ');
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('bank_accounts', function (Blueprint $table) {
            if (Schema::hasColumn('bank_accounts', 'company_id')) {
                // Drop the index first
                $table->dropIndex(['company_id', 'is_active']);

                // Drop the foreign key constraint
                $table->dropForeign(['company_id']);

                // Drop the column
                $table->dropColumn('company_id');
            }
        });
    }
};
