<?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
    {
        if (! Schema::hasTable('baseline_snapshot_items')) {
            return;
        }

        Schema::table('baseline_snapshot_items', function (Blueprint $table): void {
            if (! Schema::hasColumn('baseline_snapshot_items', 'subject_key')) {
                $table->string('subject_key')->nullable()->after('subject_external_id');
            }
        });

        Schema::table('baseline_snapshot_items', function (Blueprint $table): void {
            if (Schema::hasColumn('baseline_snapshot_items', 'subject_key')) {
                $table->index(['baseline_snapshot_id', 'policy_type', 'subject_key'], 'baseline_snapshot_items_subject_key_idx');
            }
        });
    }

    public function down(): void
    {
        if (! Schema::hasTable('baseline_snapshot_items')) {
            return;
        }

        Schema::table('baseline_snapshot_items', function (Blueprint $table): void {
            if (Schema::hasColumn('baseline_snapshot_items', 'subject_key')) {
                $table->dropIndex('baseline_snapshot_items_subject_key_idx');
                $table->dropColumn('subject_key');
            }
        });
    }
};
