<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * Fix the division_deliveries table to reference project_divisions instead of departments
     */
    public function up(): void
    {
        // First, truncate the division_deliveries table since the data references wrong IDs
        DB::table('division_deliveries')->truncate();

        // Drop the existing foreign key constraint
        Schema::table('division_deliveries', function (Blueprint $table) {
            $table->dropForeign(['division_id']);
        });

        // Add new foreign key constraint to project_divisions
        Schema::table('division_deliveries', function (Blueprint $table) {
            $table->foreign('division_id')
                  ->references('id')
                  ->on('project_divisions')
                  ->onDelete('restrict');
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        // Drop the project_divisions foreign key
        Schema::table('division_deliveries', function (Blueprint $table) {
            $table->dropForeign(['division_id']);
        });

        // Restore the departments foreign key
        Schema::table('division_deliveries', function (Blueprint $table) {
            $table->foreign('division_id')
                  ->references('id')
                  ->on('departments')
                  ->onDelete('restrict');
        });
    }
};
