<?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('baseline_snapshots', function (Blueprint $table): void {
            $table->id();
            $table->foreignId('workspace_id')->constrained('workspaces')->cascadeOnDelete();
            $table->foreignId('baseline_profile_id')->constrained('baseline_profiles')->cascadeOnDelete();
            $table->string('snapshot_identity_hash', 64);
            $table->timestampTz('captured_at');
            $table->jsonb('summary_jsonb')->nullable();
            $table->timestamps();

            $table->unique(['workspace_id', 'baseline_profile_id', 'snapshot_identity_hash'], 'baseline_snapshots_dedupe_unique');
            $table->index(['workspace_id', 'baseline_profile_id', 'captured_at'], 'baseline_snapshots_lookup_idx');
        });

        Schema::table('baseline_profiles', function (Blueprint $table): void {
            $table->foreign('active_snapshot_id')
                ->references('id')
                ->on('baseline_snapshots')
                ->nullOnDelete();
        });
    }

    public function down(): void
    {
        Schema::table('baseline_profiles', function (Blueprint $table): void {
            $table->dropForeign(['active_snapshot_id']);
        });

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