<?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('similar_artwork_events', function (Blueprint $table): void {
            $table->id();
            $table->date('event_date')->index();
            $table->string('event_type', 16)->index(); // impression|click
            $table->string('algo_version', 64)->index();
            $table->foreignId('source_artwork_id')->constrained('artworks')->cascadeOnDelete();
            $table->foreignId('similar_artwork_id')->nullable()->constrained('artworks')->nullOnDelete();
            $table->unsignedSmallInteger('position')->nullable();
            $table->unsignedSmallInteger('items_count')->nullable();
            $table->timestamp('occurred_at')->nullable()->index();
            $table->timestamps();

            $table->index(['event_date', 'algo_version', 'event_type'], 'similar_artwork_events_daily_idx');
        });

        Schema::create('similar_artwork_daily_metrics', function (Blueprint $table): void {
            $table->id();
            $table->date('metric_date');
            $table->string('algo_version', 64);
            $table->unsignedInteger('impressions')->default(0);
            $table->unsignedInteger('clicks')->default(0);
            $table->decimal('ctr', 8, 6)->default(0);
            $table->timestamps();

            $table->unique(['metric_date', 'algo_version'], 'similar_artwork_daily_metrics_unique');
            $table->index(['metric_date', 'algo_version'], 'similar_artwork_daily_metrics_lookup_idx');
        });
    }

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