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

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

            $table->string('selection_key');
            $table->string('slot_key')->nullable();

            $table->string('status');

            $table->string('error_code')->nullable();
            $table->string('error_category')->nullable();
            $table->text('error_summary')->nullable();

            $table->boolean('safety_stop_triggered')->default(false);
            $table->string('safety_stop_reason')->nullable();

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

            $table->foreignId('initiator_user_id')->nullable()->constrained('users')->nullOnDelete();

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

            $table->timestamps();

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

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