<?php

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

/**
 * Rework / comeback tracking (quality KPI feeding the ISO 9001 NCR→CAPA loop).
 * A repair order can be flagged as a return of a prior job: the rework rate is a
 * core workshop quality metric, and a flagged comeback can be escalated into a
 * Non-Conformance Report (rework_ncr_id) so corrective action is tracked.
 */
return new class extends Migration {
    public function up(): void
    {
        if (! Schema::hasTable('vrc_repair_orders')) {
            return;
        }
        Schema::table('vrc_repair_orders', function (Blueprint $t) {
            if (! Schema::hasColumn('vrc_repair_orders', 'is_rework')) {
                $t->boolean('is_rework')->default(false)->after('priority');
            }
            if (! Schema::hasColumn('vrc_repair_orders', 'rework_of_id')) {
                $t->unsignedBigInteger('rework_of_id')->nullable()->after('is_rework');
                $t->index('rework_of_id');
            }
            if (! Schema::hasColumn('vrc_repair_orders', 'rework_reason')) {
                $t->string('rework_reason', 255)->nullable()->after('rework_of_id');
            }
            if (! Schema::hasColumn('vrc_repair_orders', 'rework_ncr_id')) {
                $t->unsignedBigInteger('rework_ncr_id')->nullable()->after('rework_reason');
            }
        });
    }

    public function down(): void
    {
        if (! Schema::hasTable('vrc_repair_orders')) {
            return;
        }
        Schema::table('vrc_repair_orders', function (Blueprint $t) {
            if (Schema::hasColumn('vrc_repair_orders', 'rework_of_id')) {
                $t->dropIndex(['rework_of_id']);
            }
            foreach (['is_rework', 'rework_of_id', 'rework_reason', 'rework_ncr_id'] as $col) {
                if (Schema::hasColumn('vrc_repair_orders', $col)) {
                    $t->dropColumn($col);
                }
            }
        });
    }
};
