<?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
{
    /**
     * Merge is standalone: no work order master/details created.
     * Add date, note to merge; make merged_work_order_id nullable.
     */
    public function up(): void
    {
        Schema::table('work_order_merges', function (Blueprint $table) {
            $table->date('date')->nullable()->after('source_work_order_ids');
            $table->text('note')->nullable()->after('date');
        });

        Schema::table('work_order_merges', function (Blueprint $table) {
            $table->dropForeign(['merged_work_order_id']);
        });

        DB::statement('ALTER TABLE work_order_merges MODIFY merged_work_order_id BIGINT UNSIGNED NULL');

        Schema::table('work_order_merges', function (Blueprint $table) {
            $table->foreign('merged_work_order_id')
                ->references('id')
                ->on('work_order_masters')
                ->onDelete('set null');
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::table('work_order_merges', function (Blueprint $table) {
            $table->dropForeign(['merged_work_order_id']);
        });

        Schema::table('work_order_merges', function (Blueprint $table) {
            $table->dropColumn(['date', 'note']);
        });

        DB::statement('ALTER TABLE work_order_merges MODIFY merged_work_order_id BIGINT UNSIGNED NOT NULL');

        Schema::table('work_order_merges', function (Blueprint $table) {
            $table->foreign('merged_work_order_id')
                ->references('id')
                ->on('work_order_masters')
                ->onDelete('cascade');
        });
    }
};
