<?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) {
            if (!Schema::hasColumn('companies', 'parent_company_id')) {
                $table->foreignId('parent_company_id')->nullable()->after('id')->constrained('companies')->onDelete('set null');
            }
            if (!Schema::hasColumn('companies', 'is_holding_company')) {
                $table->boolean('is_holding_company')->default(false)->after('status');
            }
            if (!Schema::hasColumn('companies', 'cash_balance')) {
                $table->decimal('cash_balance', 15, 2)->default(0)->after('employee_count');
            }
            if (!Schema::hasColumn('companies', 'runway_days')) {
                $table->integer('runway_days')->nullable()->after('cash_balance');
            }
            if (!Schema::hasColumn('companies', 'credit_score')) {
                $table->integer('credit_score')->default(500)->after('runway_days');
            }
            if (!Schema::hasColumn('companies', 'total_assets')) {
                $table->decimal('total_assets', 15, 2)->default(0)->after('credit_score');
            }
            if (!Schema::hasColumn('companies', 'total_liabilities')) {
                $table->decimal('total_liabilities', 15, 2)->default(0)->after('total_assets');
            }
            if (!Schema::hasColumn('companies', 'last_health_check')) {
                $table->date('last_health_check')->nullable()->after('total_liabilities');
            }
            if (!Schema::hasColumn('companies', 'health_status')) {
                $table->enum('health_status', ['excellent', 'good', 'fair', 'poor', 'critical'])->default('good')->after('last_health_check');
            }

            // Idempotent indexes
            try { $table->index('parent_company_id'); } catch (\Exception $e) {}
            try { $table->index('is_holding_company'); } catch (\Exception $e) {}
            try { $table->index('health_status'); } catch (\Exception $e) {}
        });
    }

    public function down(): void
    {
        Schema::table('companies', function (Blueprint $table) {
            $table->dropForeign(['parent_company_id']);
            $table->dropColumn([
                'parent_company_id',
                'is_holding_company',
                'cash_balance',
                'runway_days',
                'credit_score',
                'total_assets',
                'total_liabilities',
                'last_health_check',
                'health_status'
            ]);
        });
    }
};
