<?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
    {
        // M13: work_photos polymorphic table (per work line OR per part line OR WO-level)
        Schema::create('work_photos', function (Blueprint $t) {
            $t->id();
            $t->foreignId('company_id')->constrained()->cascadeOnDelete();
            $t->foreignId('work_order_id')->constrained()->cascadeOnDelete();
            $t->morphs('subject');                      // WorkOrderWork | WorkOrderPart | WorkOrder
            $t->foreignId('uploaded_by_id')->nullable()->constrained('users')->nullOnDelete();
            $t->string('path', 500);                    // storage path
            $t->string('type', 16)->default('general'); // defect | before | after | general
            $t->text('caption')->nullable();
            $t->timestamp('taken_at')->nullable();
            $t->timestamps();
            $t->index(['company_id', 'work_order_id']);
        });

        // M13: e-signature + barcode scan on warehouse events
        Schema::table('warehouse_events', function (Blueprint $t) {
            if (! Schema::hasColumn('warehouse_events', 'signature_b64')) {
                $t->longText('signature_b64')->nullable();
            }
            if (! Schema::hasColumn('warehouse_events', 'scan_payload')) {
                $t->string('scan_payload', 255)->nullable();
            }
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('work_photos');
        Schema::table('warehouse_events', function (Blueprint $t) {
            foreach (['signature_b64', 'scan_payload'] as $col) {
                if (Schema::hasColumn('warehouse_events', $col)) $t->dropColumn($col);
            }
        });
    }
};
