<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('bulk_operation_runs', function (Blueprint $table) {
            $table->id();
            $table->foreignId('managed_environment_id')->constrained()->cascadeOnDelete();
            $table->foreignId('user_id')->constrained()->cascadeOnDelete();
            $table->string('resource', 50);
            $table->string('action', 50);
            $table->string('status', 20)->default('pending');
            $table->unsignedInteger('total_items');
            $table->unsignedInteger('processed_items')->default(0);
            $table->unsignedInteger('succeeded')->default(0);
            $table->unsignedInteger('failed')->default(0);
            $table->unsignedInteger('skipped')->default(0);
            $table->jsonb('item_ids');
            $table->jsonb('failures')->nullable();
            $table->foreignId('audit_log_id')->nullable()->constrained()->nullOnDelete();
            $table->timestamps();
        });

        Schema::table('bulk_operation_runs', function (Blueprint $table) {
            $table->index(['managed_environment_id', 'resource', 'status'], 'bulk_runs_tenant_resource_status');
            $table->index(['user_id', 'created_at'], 'bulk_runs_user_created');
        });

        DB::statement("CREATE INDEX bulk_runs_status_active ON bulk_operation_runs (status) WHERE status IN ('pending', 'running')");
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        DB::statement('DROP INDEX IF EXISTS bulk_runs_status_active');

        Schema::dropIfExists('bulk_operation_runs');
    }
};
