<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

/**
 * Persistent view event log.
 *
 * Stores one row per view — authenticated users get a user_id, guests are
 * recorded with user_id = null. Enables:
 *   - "Recently viewed" per user
 *   - Exact windowed counts (replayable)
 *   - Unique-viewer counts per artwork
 *
 * Rows older than 90 days are pruned by the weekly
 * skinbase:prune-view-events command.
 */
return new class extends Migration
{
    public function up(): void
    {
        Schema::create('artwork_view_events', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('artwork_id');
            $table->unsignedBigInteger('user_id')->nullable(); // null = guest

            $table->timestamp('viewed_at')->useCurrent();

            // Windowed aggregate queries: COUNT(*) WHERE artwork_id=? AND viewed_at>=?
            $table->index(['artwork_id', 'viewed_at']);
            // Per-user history: recent artworks viewed by a user
            $table->index(['user_id', 'viewed_at']);
            // Pruning: DELETE WHERE viewed_at < cutoff
            $table->index('viewed_at');

            $table->foreign('artwork_id')
                ->references('id')->on('artworks')
                ->cascadeOnDelete();

            $table->foreign('user_id')
                ->references('id')->on('users')
                ->nullOnDelete();
        });
    }

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