<?php

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

/**
 * Quality-control: reusable checklists (templates) and per-booking inspections
 * run at a stage (setup / pre-event / post-event). A failed/open inspection can
 * gate booking completion.
 */
return new class extends Migration {
    public function up(): void
    {
        if (! Schema::hasTable('bms_qc_checklists')) {
            Schema::create('bms_qc_checklists', function (Blueprint $t) {
                $t->bigIncrements('id');
                $t->unsignedInteger('business_id');
                $t->string('name', 120);
                $t->string('name_ar', 120)->nullable();
                $t->string('event_type', 60)->nullable(); // null = any
                $t->string('stage', 20)->default('pre_event');
                $t->json('items')->nullable(); // [{label, label_ar}]
                $t->boolean('is_active')->default(true);
                $t->unsignedInteger('sort_order')->default(0);
                $t->timestamps();
                $t->index(['business_id', 'is_active']);
            });
        }

        if (! Schema::hasTable('bms_qc_inspections')) {
            Schema::create('bms_qc_inspections', function (Blueprint $t) {
                $t->bigIncrements('id');
                $t->unsignedInteger('business_id');
                $t->unsignedBigInteger('booking_id');
                $t->unsignedBigInteger('checklist_id')->nullable();
                $t->string('stage', 20)->default('pre_event');
                $t->json('items')->nullable(); // [{label, status:pass|fail|na, note}]
                $t->unsignedInteger('score')->nullable(); // 0..100
                $t->enum('status', ['open', 'passed', 'failed'])->default('open');
                $t->unsignedInteger('inspector_id')->nullable();
                $t->dateTime('completed_at')->nullable();
                $t->timestamps();
                $t->index(['business_id', 'booking_id']);
                $t->index(['business_id', 'status']);
            });
        }
    }

    public function down(): void
    {
        Schema::dropIfExists('bms_qc_inspections');
        Schema::dropIfExists('bms_qc_checklists');
    }
};
