<?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.
     */
    public function up(): void
    {
        // Find the holding company
        $holdingCompany = DB::table('companies')->where('is_holding_company', true)->first();
        
        if ($holdingCompany) {
            // Migrate existing loans from holding company to Super Admin
            DB::table('intercompany_loans')
                ->where('lender_company_id', $holdingCompany->id)
                ->update([
                    'lender_company_id' => null,
                    'is_super_admin_lender' => true,
                ]);
            
            // Migrate existing profit sweeps to Super Admin
            DB::table('profit_sweep_transactions')
                ->where('to_company_id', $holdingCompany->id)
                ->update([
                    'to_company_id' => null,
                    'is_super_admin_recipient' => true,
                ]);
            
            // Migrate profit sweep rules to Super Admin
            DB::table('profit_sweep_rules')
                ->where('parent_company_id', $holdingCompany->id)
                ->update([
                    'parent_company_id' => null,
                ]);
            
            // Remove is_holding_company flag from all companies
            DB::table('companies')->update(['is_holding_company' => false]);
        }
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        // This migration is not easily reversible as we're changing the architecture
        // In production, you would need to restore from backup
    }
};
