<?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('stored_reports', function (Blueprint $table) {
            $table->id();
            $table->foreignId('workspace_id')->constrained()->cascadeOnDelete();
            $table->foreignId('managed_environment_id')->constrained()->cascadeOnDelete();
            $table->string('report_type');
            $table->jsonb('payload');
            $table->timestamps();

            $table->index(['workspace_id', 'managed_environment_id', 'report_type']);
            $table->index(['managed_environment_id', 'created_at']);
        });

        if (DB::getDriverName() === 'pgsql') {
            DB::statement('CREATE INDEX stored_reports_payload_gin ON stored_reports USING GIN (payload)');
        }
    }

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