<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        // Default dsar_type_id to 6 (Care Setting) for any institutions without one
        DB::table('institutions')->whereNull('dsar_type_id')->update(['dsar_type_id' => 6]);

        // Drop institution_type_id from institutions
        Schema::table('institutions', function (Blueprint $table) {
            $table->dropForeign(['institution_type_id']);
            $table->dropColumn('institution_type_id');
        });

        // Drop record_type_id from claim_institution
        Schema::table('claim_institution', function (Blueprint $table) {
            $table->dropForeign(['record_type_id']);
            $table->dropColumn('record_type_id');
        });
    }

    public function down(): void
    {
        Schema::table('institutions', function (Blueprint $table) {
            $table->foreignId('institution_type_id')->after('slug')->constrained('institution_types');
        });

        Schema::table('claim_institution', function (Blueprint $table) {
            $table->foreignId('record_type_id')->nullable()->constrained('institution_record_types')->nullOnDelete();
        });
    }
};
