<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        // Workflow templates (versioned, immutable when published)
        Schema::create('workflow_templates', function (Blueprint $table) {
            $table->id();
            $table->foreignIdFor(\App\Models\Org::class)
                ->nullable()->constrained()->nullOnDelete();
            $table->string('name');
            $table->string('subject_type'); // e.g., App\Models\Order
            $table->enum('status', ['draft', 'published', 'archived'])->default('draft');
            $table->integer('version')->default(1);
            $table->boolean('is_active')->default(true);
            $table->timestamp('published_at')->nullable();
            $table->softDeletes();
            $table->timestamps();

            $table->index(['org_id', 'subject_type']);
            $table->index(['org_id', 'subject_type', 'is_active']);
        });

        // Step templates within workflow templates
        Schema::create('step_templates', function (Blueprint $table) {
            $table->id();
            $table->foreignId('workflow_template_id')->constrained()->cascadeOnDelete();
            $table->integer('position');
            $table->enum('type', ['approval', 'input', 'auto'])->default('approval');
            $table->string('system_key')->nullable(); // e.g., 'launched' for required steps
            $table->string('label');
            $table->json('form_definition')->nullable();
            $table->json('validation')->nullable(); // Custom validation rules
            $table->json('data_bindings')->nullable(); // Map form data to domain models
            $table->string('handler')->nullable(); // Handler class name
            $table->boolean('is_locked')->default(false); // Locked when published
            $table->softDeletes();
            $table->timestamps();

            $table->index(['workflow_template_id', 'position']);
        });

        // Runtime workflow instances per subject
        Schema::create('workflow_instances', function (Blueprint $table) {
            $table->id();
            $table->foreignId('workflow_template_id')->constrained()->cascadeOnDelete();
            $table->foreignIdFor(\App\Models\Org::class)
                ->nullable()->constrained()->nullOnDelete();
            $table->string('subject_type');
            $table->unsignedBigInteger('subject_id');
            $table->enum('state', ['running', 'completed', 'rejected', 'canceled'])->default('running');
            $table->softDeletes();
            $table->timestamps();

            $table->index(['subject_type', 'subject_id']);
            $table->index(['org_id', 'state']);
        });

        // Step instances for audit trail
        Schema::create('step_instances', function (Blueprint $table) {
            $table->id();
            $table->foreignId('workflow_instance_id')->constrained()->cascadeOnDelete();
            $table->foreignId('step_template_id')->constrained()->cascadeOnDelete();
            $table->enum('status', ['pending', 'approved', 'rejected', 'skipped'])->default('pending');
            $table->foreignId('acted_by')->nullable()->constrained('users')->nullOnDelete();
            $table->timestamp('acted_at')->nullable();
            $table->json('data')->nullable(); // Form submission data
            $table->text('note')->nullable(); // Notes or rejection reason
            $table->json('step_template_snapshot'); // Snapshot of step template at creation
            $table->softDeletes();
            $table->timestamps();

            $table->index(['workflow_instance_id', 'status']);
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('step_instances');
        Schema::dropIfExists('workflow_instances');
        Schema::dropIfExists('step_templates');
        Schema::dropIfExists('workflow_templates');
    }
};
