<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * This migration updates the stock_movements table's division_id foreign key
     * to reference project_divisions instead of departments.
     */
    public function up(): void
    {
        Schema::table('stock_movements', function (Blueprint $table) {
            // Drop the old foreign key constraint that references departments
            $table->dropForeign(['division_id']);
        });

        Schema::table('stock_movements', function (Blueprint $table) {
            // Add new foreign key constraint that references project_divisions
            $table->foreign('division_id')
                  ->references('id')
                  ->on('project_divisions')
                  ->onDelete('set null');
        });
    }

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

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