<?php

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

return new class extends Migration
{
    /**
     * Add playlist view tracking — mirrors the video_views pattern.
     *
     *  • playlists.view_count   — denormalised total for fast card rendering
     *  • playlist_views table   — one row per (playlist, viewer-id) so a refresh
     *                             within the dedup window doesn't double-count
     */
    public function up(): void
    {
        Schema::table('playlists', function (Blueprint $table) {
            $table->unsignedBigInteger('view_count')->default(0)->after('share_token');
        });

        Schema::create('playlist_views', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('playlist_id');
            $table->unsignedBigInteger('user_id')->nullable();
            $table->string('device_id', 64)->nullable();
            $table->string('device_hash', 64)->nullable();
            $table->string('ip_address', 64)->nullable();
            $table->string('country', 8)->nullable();
            $table->string('country_name', 64)->nullable();
            $table->string('user_agent', 512)->nullable();
            $table->timestamp('viewed_at');

            $table->foreign('playlist_id')->references('id')->on('playlists')->onDelete('cascade');
            $table->index(['playlist_id', 'viewed_at']);
            $table->index(['playlist_id', 'user_id', 'viewed_at']);
            $table->index(['playlist_id', 'device_id', 'viewed_at']);
            $table->index(['playlist_id', 'device_hash', 'viewed_at']);
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('playlist_views');
        Schema::table('playlists', function (Blueprint $table) {
            $table->dropColumn('view_count');
        });
    }
};
