<?php

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

/**
 * Repair orders / job cards (spec §5.3) — the spine of the module. Header +
 * service lines + part lines + labor logs + status history. References to ERP
 * rows (customer, product, stock movement, invoice, user) are plain indexed
 * columns (no FK), matching the module convention.
 */
return new class extends Migration {
    public function up(): void
    {
        if (! Schema::hasTable('vrc_repair_orders')) {
            Schema::create('vrc_repair_orders', function (Blueprint $t) {
                $t->bigIncrements('id');
                $t->unsignedInteger('business_id');
                $t->unsignedInteger('location_id')->nullable();
                $t->string('number', 60)->nullable();
                $t->unsignedInteger('erp_customer_id');
                $t->unsignedBigInteger('vehicle_id');
                $t->unsignedBigInteger('appointment_id')->nullable();
                $t->string('status', 30)->default('draft');
                $t->string('priority', 20)->default('normal'); // low|normal|high|urgent
                $t->unsignedInteger('service_advisor_id')->nullable(); // ERP user
                $t->unsignedBigInteger('bay_id')->nullable();
                $t->unsignedInteger('odometer_in')->nullable();
                $t->unsignedTinyInteger('fuel_level_in')->nullable(); // 0-100 (%)
                $t->text('customer_concerns')->nullable();
                $t->text('internal_notes')->nullable();
                $t->dateTime('promised_at')->nullable();
                $t->dateTime('checked_in_at')->nullable();
                $t->dateTime('work_started_at')->nullable();
                $t->dateTime('completed_at')->nullable();
                $t->dateTime('delivered_at')->nullable();
                $t->unsignedBigInteger('estimate_id')->nullable();
                $t->unsignedBigInteger('erp_invoice_id')->nullable(); // ERP transaction id
                $t->decimal('subtotal', 15, 2)->default(0);
                $t->decimal('discount_total', 15, 2)->default(0);
                $t->decimal('tax_total', 15, 2)->default(0);
                $t->decimal('grand_total', 15, 2)->default(0);
                $t->string('currency', 5)->nullable();
                $t->unsignedInteger('created_by')->nullable();
                $t->timestamps();
                $t->softDeletes();
                $t->index(['business_id', 'status']);
                $t->index(['business_id', 'vehicle_id']);
                $t->index(['business_id', 'erp_customer_id']);
                $t->index(['business_id', 'number']);
            });
        }

        if (! Schema::hasTable('vrc_repair_order_services')) {
            Schema::create('vrc_repair_order_services', function (Blueprint $t) {
                $t->bigIncrements('id');
                $t->unsignedInteger('business_id');
                $t->unsignedBigInteger('repair_order_id');
                $t->unsignedBigInteger('service_id')->nullable(); // vrc_services (nullable = ad-hoc)
                $t->string('description', 255);
                $t->decimal('labor_hours', 8, 2)->default(0);
                $t->decimal('labor_rate', 15, 2)->default(0);
                $t->decimal('qty', 8, 2)->default(1);
                $t->decimal('unit_price', 15, 2)->default(0);
                $t->decimal('discount', 15, 2)->default(0);
                $t->string('discount_type', 12)->default('fixed');
                $t->unsignedBigInteger('tax_rate_id')->nullable();
                $t->decimal('line_total', 15, 2)->default(0);
                $t->string('status', 20)->default('pending'); // pending|in_progress|done|skipped
                $t->unsignedInteger('assigned_technician_id')->nullable();
                $t->integer('sort_order')->default(0);
                $t->timestamps();
                $t->index(['business_id', 'repair_order_id']);
            });
        }

        if (! Schema::hasTable('vrc_repair_order_parts')) {
            Schema::create('vrc_repair_order_parts', function (Blueprint $t) {
                $t->bigIncrements('id');
                $t->unsignedInteger('business_id');
                $t->unsignedBigInteger('repair_order_id');
                $t->unsignedInteger('erp_product_id')->nullable();
                $t->unsignedInteger('erp_variation_id')->nullable();
                $t->string('description', 255);
                $t->decimal('qty', 8, 2)->default(1);
                $t->decimal('unit_cost', 15, 2)->default(0);
                $t->decimal('unit_price', 15, 2)->default(0);
                $t->decimal('discount', 15, 2)->default(0);
                $t->string('discount_type', 12)->default('fixed');
                $t->unsignedBigInteger('tax_rate_id')->nullable();
                $t->decimal('line_total', 15, 2)->default(0);
                $t->string('source', 20)->default('stock'); // stock|special_order|customer_supplied
                $t->unsignedBigInteger('erp_stock_movement_id')->nullable();
                $t->unsignedInteger('warranty_months')->nullable();
                $t->integer('sort_order')->default(0);
                $t->timestamps();
                $t->index(['business_id', 'repair_order_id']);
            });
        }

        if (! Schema::hasTable('vrc_repair_order_labor_logs')) {
            Schema::create('vrc_repair_order_labor_logs', function (Blueprint $t) {
                $t->bigIncrements('id');
                $t->unsignedInteger('business_id');
                $t->unsignedBigInteger('repair_order_id');
                $t->unsignedBigInteger('repair_order_service_id')->nullable();
                $t->unsignedInteger('technician_id'); // ERP user (Phase 8: vrc_technicians)
                $t->dateTime('started_at');
                $t->dateTime('ended_at')->nullable();
                $t->unsignedInteger('duration_min')->nullable();
                $t->string('note', 255)->nullable();
                $t->timestamps();
                $t->index(['business_id', 'repair_order_id']);
                $t->index(['business_id', 'technician_id']);
            });
        }

        if (! Schema::hasTable('vrc_repair_order_status_history')) {
            Schema::create('vrc_repair_order_status_history', function (Blueprint $t) {
                $t->bigIncrements('id');
                $t->unsignedInteger('business_id');
                $t->unsignedBigInteger('repair_order_id');
                $t->string('from_status', 30)->nullable();
                $t->string('to_status', 30);
                $t->unsignedInteger('actor_id')->nullable(); // ERP user
                $t->string('reason', 255)->nullable();
                $t->json('meta')->nullable();
                $t->timestamp('created_at')->nullable();
                $t->index(['business_id', 'repair_order_id'], 'vrc_ro_status_hist_biz_ro_idx');
            });
        }
    }

    public function down(): void
    {
        Schema::dropIfExists('vrc_repair_order_status_history');
        Schema::dropIfExists('vrc_repair_order_labor_logs');
        Schema::dropIfExists('vrc_repair_order_parts');
        Schema::dropIfExists('vrc_repair_order_services');
        Schema::dropIfExists('vrc_repair_orders');
    }
};
