<?php

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

return new class extends Migration
{
    public function up(): void
    {
        // M12: separate body_type + transmission_type on vehicles
        Schema::table('vehicles', function (Blueprint $t) {
            if (! Schema::hasColumn('vehicles', 'body_type')) {
                $t->string('body_type', 16)->nullable()->after('vehicle_class');
                // sedan | hatchback | suv | crossover | pickup | van | truck | coupe | wagon | convertible | minivan | moto
            }
            if (! Schema::hasColumn('vehicles', 'transmission_type')) {
                $t->string('transmission_type', 16)->nullable()->after('body_type');
                // manual | automatic | cvt | dsg | dct | amt | robot
            }
        });

        // M12: pricing application audit log
        Schema::create('pricing_application_logs', function (Blueprint $t) {
            $t->id();
            $t->foreignId('company_id')->constrained()->cascadeOnDelete();
            $t->morphs('subject');                   // WorkOrderPart or WorkOrderWork
            $t->foreignId('part_id')->nullable()->constrained('parts')->nullOnDelete();
            $t->foreignId('vehicle_id')->nullable()->constrained('vehicles')->nullOnDelete();
            $t->foreignId('client_id')->nullable()->constrained('clients')->nullOnDelete();
            $t->decimal('base_price', 12, 2);
            $t->decimal('final_price', 12, 2);
            $t->json('applied_coefficients');        // [{name, multiplier, type}, ...]
            $t->json('context');                     // {class, age, body_type, transmission, vip, urgency}
            $t->timestamp('calculated_at')->useCurrent();
        });

        // M14: ocr_jobs queue
        Schema::create('ocr_jobs', function (Blueprint $t) {
            $t->id();
            $t->foreignId('company_id')->constrained()->cascadeOnDelete();
            $t->foreignId('supplier_id')->nullable()->constrained('suppliers')->nullOnDelete();
            $t->string('source_type', 16);   // pdf | image | xlsx | barcode_scan
            $t->string('file_path', 500)->nullable();   // storage path
            $t->string('status', 16)->default('pending');   // pending|processing|done|failed
            $t->json('result')->nullable();
            $t->text('error_message')->nullable();
            $t->string('ai_provider', 32)->nullable();
            $t->integer('tokens_used')->nullable();
            $t->foreignId('purchase_id')->nullable()->constrained('purchases')->nullOnDelete();
            $t->timestamp('processed_at')->nullable();
            $t->timestamps();
            $t->index(['company_id', 'status']);
        });

        // M15: eta_promised distinct from eta_at + change reason audit
        Schema::table('work_orders', function (Blueprint $t) {
            if (! Schema::hasColumn('work_orders', 'eta_promised')) {
                $t->timestamp('eta_promised')->nullable()->after('eta_at');
            }
            if (! Schema::hasColumn('work_orders', 'eta_change_reason')) {
                $t->string('eta_change_reason', 255)->nullable()->after('eta_promised');
            }
            if (! Schema::hasColumn('work_orders', 'eta_updated_at')) {
                $t->timestamp('eta_updated_at')->nullable()->after('eta_change_reason');
            }
        });

        // M15: client notifications log
        Schema::create('client_notifications_log', function (Blueprint $t) {
            $t->id();
            $t->foreignId('company_id')->constrained()->cascadeOnDelete();
            $t->foreignId('work_order_id')->nullable()->constrained('work_orders')->nullOnDelete();
            $t->foreignId('client_id')->nullable()->constrained('clients')->nullOnDelete();
            $t->string('channel', 16);            // sms | whatsapp | telegram | email | push
            $t->string('template_key', 64);       // wo_ready | eta_updated | approval_needed | service_reminder
            $t->text('message_text')->nullable();
            $t->string('status', 16)->default('sent');   // sent | delivered | failed | read
            $t->text('error_detail')->nullable();
            $t->timestamp('sent_at')->useCurrent();
            $t->timestamp('delivered_at')->nullable();
            $t->index(['company_id', 'sent_at']);
            $t->index(['work_order_id', 'sent_at']);
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('client_notifications_log');
        Schema::dropIfExists('ocr_jobs');
        Schema::dropIfExists('pricing_application_logs');
        Schema::table('vehicles', function (Blueprint $t) {
            foreach (['body_type', 'transmission_type'] as $col) {
                if (Schema::hasColumn('vehicles', $col)) $t->dropColumn($col);
            }
        });
        Schema::table('work_orders', function (Blueprint $t) {
            foreach (['eta_promised', 'eta_change_reason', 'eta_updated_at'] as $col) {
                if (Schema::hasColumn('work_orders', $col)) $t->dropColumn($col);
            }
        });
    }
};
