<?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('product_usage_events', function (Blueprint $table): void {
            $table->id();
            $table->foreignId('workspace_id')->constrained()->cascadeOnDelete();
            $table->foreignId('managed_environment_id')->constrained()->cascadeOnDelete();
            $table->foreignId('user_id')->nullable()->constrained()->nullOnDelete();
            $table->string('event_name', 120);
            $table->string('feature_area', 60);
            $table->string('subject_type', 120);
            $table->string('subject_id', 120);
            $table->jsonb('metadata')->default('{}');
            $table->timestampTz('occurred_at');
            $table->timestamps();

            $table->index(['workspace_id', 'managed_environment_id', 'occurred_at']);
            $table->index(['event_name', 'occurred_at']);
            $table->index(['subject_type', 'subject_id', 'occurred_at']);
        });
    }

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