<?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('page_views', function (Blueprint $table) {
            $table->id();

            // Anonymous visitor tracking — UUID stored in visitor's localStorage
            $table->string('visitor_id', 36)->comment('UUID persisted in localStorage across sessions');
            // Per-tab session identifier stored in sessionStorage
            $table->string('session_id', 36)->comment('UUID per browser tab session');

            // Page URL path (e.g. "/", "/pricing", "/dashboard")
            $table->string('page', 500);
            // Document referrer (the URL they came from)
            $table->string('referrer', 500)->nullable();

            // Network
            $table->string('ip_address', 45)->nullable();

            // Geo — resolved asynchronously from the IP
            $table->char('country_code', 2)->nullable();
            $table->string('country_name', 100)->nullable();
            $table->string('city', 100)->nullable();

            // How long the user stayed on this specific page (seconds)
            $table->unsignedSmallInteger('duration_seconds')->nullable();

            // Device / browser
            $table->string('user_agent', 300)->nullable();

            // Whether the visitor was authenticated
            $table->boolean('is_authenticated')->default(false);
            $table->foreignId('organization_id')->nullable()->constrained()->nullOnDelete();

            // UTM params
            $table->string('utm_source', 100)->nullable();
            $table->string('utm_medium', 100)->nullable();
            $table->string('utm_campaign', 100)->nullable();

            $table->timestamps();

            // Performance indexes
            $table->index('visitor_id');
            $table->index('session_id');
            $table->index(['page', 'created_at']);
            $table->index('country_code');
            $table->index('created_at');
            $table->index('is_authenticated');
        });
    }

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