<?php

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

/**
 * #9 cancellation reason code (selected from an editable list, alongside the
 * free-text reason) and #7 QC activity log (bms_qc_events). QC per-item
 * reason_code / note / voice are carried in the inspection's items JSON.
 */
return new class extends Migration {
    public function up(): void
    {
        Schema::table('bms_bookings', function (Blueprint $t) {
            if (! Schema::hasColumn('bms_bookings', 'cancellation_reason_code')) {
                $t->string('cancellation_reason_code', 60)->nullable()->after('cancellation_reason');
            }
        });

        if (! Schema::hasTable('bms_qc_events')) {
            Schema::create('bms_qc_events', function (Blueprint $t) {
                $t->bigIncrements('id');
                $t->unsignedInteger('business_id');
                $t->unsignedBigInteger('inspection_id');
                $t->string('type', 20); // started|item|submitted|note|voice
                $t->string('detail', 500)->nullable();
                $t->unsignedInteger('user_id')->nullable();
                $t->timestamps();
                $t->index(['business_id', 'inspection_id']);
            });
        }
    }

    public function down(): void
    {
        Schema::dropIfExists('bms_qc_events');
        Schema::table('bms_bookings', function (Blueprint $t) {
            if (Schema::hasColumn('bms_bookings', 'cancellation_reason_code')) {
                $t->dropColumn('cancellation_reason_code');
            }
        });
    }
};
