<?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
    {
        Schema::table('companies', function (Blueprint $table) {
            // Add unique constraint to ensure only one holding company
            // This will be enforced at application level, but we add an index
            if (!Schema::hasColumn('companies', 'is_holding_company')) {
                $table->boolean('is_holding_company')->default(false)->after('status');
            }
        });

        // Ensure only one holding company exists
        DB::statement("
            UPDATE companies 
            SET is_holding_company = false 
            WHERE id NOT IN (
                SELECT id FROM (
                    SELECT id FROM companies 
                    WHERE is_holding_company = true 
                    ORDER BY id 
                    LIMIT 1
                ) as temp
            )
        ");
    }

    public function down(): void
    {
        // No rollback needed for this logic
    }
};
