<?php

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

/**
 * Workshop resources (bays — spec §5.2/§6.9) and appointments/scheduling
 * (spec §5.2/§6.2). appointment.repair_order_id links to the RO created at
 * check-in (RO table arrives in Phase 4; column is a plain nullable ref).
 */
return new class extends Migration {
    public function up(): void
    {
        if (! Schema::hasTable('vrc_bays')) {
            Schema::create('vrc_bays', function (Blueprint $t) {
                $t->bigIncrements('id');
                $t->unsignedInteger('business_id');
                $t->unsignedInteger('location_id')->nullable(); // ERP business_location
                $t->string('name', 191);
                $t->string('type', 20)->default('bay'); // lift|bay|wash|diagnostic
                $t->boolean('is_active')->default(true);
                $t->integer('sort_order')->default(0);
                $t->timestamps();
                $t->index(['business_id', 'is_active']);
            });
        }

        if (! Schema::hasTable('vrc_appointments')) {
            Schema::create('vrc_appointments', function (Blueprint $t) {
                $t->bigIncrements('id');
                $t->unsignedInteger('business_id');
                $t->unsignedInteger('location_id')->nullable();
                $t->unsignedInteger('erp_customer_id')->nullable();
                $t->unsignedBigInteger('vehicle_id')->nullable();      // nullable for new vehicle
                $t->unsignedBigInteger('bay_id')->nullable();
                $t->unsignedInteger('assigned_technician_id')->nullable();
                $t->dateTime('scheduled_start');
                $t->dateTime('scheduled_end')->nullable();
                $t->string('status', 20)->default('requested'); // requested|confirmed|rescheduled|checked_in|no_show|cancelled|completed
                $t->string('source', 20)->default('phone');      // walk_in|phone|portal|web
                $t->text('concern')->nullable();
                $t->unsignedInteger('estimated_duration_min')->nullable();
                $t->unsignedBigInteger('repair_order_id')->nullable();
                $t->text('notes')->nullable();
                $t->timestamps();
                $t->index(['business_id', 'scheduled_start']);
                $t->index(['business_id', 'status']);
                $t->index(['business_id', 'bay_id']);
                $t->index(['business_id', 'vehicle_id']);
            });
        }
    }

    public function down(): void
    {
        Schema::dropIfExists('vrc_appointments');
        Schema::dropIfExists('vrc_bays');
    }
};
