<?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
    {
        Schema::create('provisioning_runs', function (Blueprint $table) {
            $table->id();
            $table->uuid('uuid')->unique();
            $table->string('subject_type');               // polymorphic subject (Host | Order …)
            $table->unsignedBigInteger('subject_id');
            $table->string('pipeline');                   // host | customer
            $table->unsignedInteger('current_step')->default(0);
            $table->string('status')->default('pending'); // pending running waiting paused completed failed
            $table->unsignedInteger('attempt')->default(0);
            $table->unsignedInteger('max_attempts')->default(5);
            $table->timestamp('next_attempt_at')->nullable();
            $table->timestamp('started_at')->nullable();
            $table->timestamp('finished_at')->nullable();
            $table->text('error')->nullable();
            $table->json('context')->nullable();
            $table->timestamps();

            $table->index(['subject_type', 'subject_id']);
            $table->index(['status', 'next_attempt_at']);
        });
    }

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