<?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('contract_configs', function (Blueprint $table) {
            // Rename initial_segment_id to segment_id
            if (Schema::hasColumn('contract_configs', 'initial_segment_id')) {
                $table->renameColumn('initial_segment_id', 'segment_id');
            }
        });

        Schema::table('contract_configs', function (Blueprint $table) {
            // Add is_initial and drop unique(contract_type_id)
            $table->boolean('is_initial')->default(false)->after('segment_id');
        });

        // Drop existing unique index on contract_type_id if present and add composite unique
        try {
            Schema::table('contract_configs', function (Blueprint $table) {
                $table->dropUnique(['contract_type_id']);
            });
        } catch (Throwable $e) {
            // ignore if index does not exist
        }

        Schema::table('contract_configs', function (Blueprint $table) {
            $table->unique(['contract_type_id', 'segment_id']);
        });

        // Mark existing rows as initial
        \DB::table('contract_configs')->update(['is_initial' => true]);
    }

    public function down(): void
    {
        // Remove composite unique
        Schema::table('contract_configs', function (Blueprint $table) {
            $table->dropUnique(['contract_type_id', 'segment_id']);
        });

        // Try to restore unique on contract_type_id
        Schema::table('contract_configs', function (Blueprint $table) {
            $table->unique('contract_type_id');
        });

        // Drop is_initial
        Schema::table('contract_configs', function (Blueprint $table) {
            $table->dropColumn('is_initial');
        });

        // Rename segment_id back to initial_segment_id
        Schema::table('contract_configs', function (Blueprint $table) {
            if (Schema::hasColumn('contract_configs', 'segment_id')) {
                $table->renameColumn('segment_id', 'initial_segment_id');
            }
        });
    }
};
