<?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('inventory_sync_runs', function (Blueprint $table) {
            $table->id();

            $table->foreignId('managed_environment_id')->constrained();

            $table->string('selection_hash', 64);
            $table->jsonb('selection_payload')->nullable();

            $table->string('status');
            $table->boolean('had_errors')->default(false);
            $table->jsonb('error_codes')->nullable();
            $table->jsonb('error_context')->nullable();

            $table->timestampTz('started_at')->nullable();
            $table->timestampTz('finished_at')->nullable();

            $table->unsignedInteger('items_observed_count')->default(0);
            $table->unsignedInteger('items_upserted_count')->default(0);
            $table->unsignedInteger('errors_count')->default(0);

            $table->timestamps();

            $table->index(['managed_environment_id', 'selection_hash']);
            $table->index(['managed_environment_id', 'status']);
            $table->index(['managed_environment_id', 'finished_at']);
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('inventory_sync_runs');
    }
};
