<?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('feed_events', function (Blueprint $table): void {
            $table->id();
            $table->date('event_date')->index();
            $table->string('event_type', 24)->index(); // feed_impression|feed_click
            $table->foreignId('user_id')->constrained('users')->cascadeOnDelete();
            $table->foreignId('artwork_id')->constrained('artworks')->cascadeOnDelete();
            $table->unsignedSmallInteger('position')->nullable();
            $table->string('algo_version', 64)->index();
            $table->string('source', 24)->index(); // personalized|cold_start|fallback
            $table->unsignedInteger('dwell_seconds')->nullable();
            $table->timestamp('occurred_at')->nullable()->index();
            $table->timestamps();

            $table->index(['event_date', 'algo_version', 'source', 'event_type'], 'feed_events_daily_agg_idx');
            $table->index(['user_id', 'artwork_id', 'event_date'], 'feed_events_user_art_date_idx');
        });

        Schema::create('feed_daily_metrics', function (Blueprint $table): void {
            $table->id();
            $table->date('metric_date');
            $table->string('algo_version', 64);
            $table->string('source', 24);

            $table->unsignedInteger('impressions')->default(0);
            $table->unsignedInteger('clicks')->default(0);
            $table->unsignedInteger('saves')->default(0);

            $table->decimal('ctr', 8, 6)->default(0);
            $table->decimal('save_rate', 8, 6)->default(0);

            $table->unsignedInteger('dwell_0_5')->default(0);
            $table->unsignedInteger('dwell_5_30')->default(0);
            $table->unsignedInteger('dwell_30_120')->default(0);
            $table->unsignedInteger('dwell_120_plus')->default(0);

            $table->timestamps();

            $table->unique(['metric_date', 'algo_version', 'source'], 'feed_daily_metrics_unique_idx');
            $table->index(['metric_date', 'algo_version', 'source'], 'feed_daily_metrics_lookup_idx');
        });
    }

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