<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('ab_tests', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('key', 191)->unique();
            $table->text('description')->nullable();
            $table->boolean('is_active')->default(false);
            $table->json('variants')->nullable(); // ['A' => 50, 'B' => 50]
            $table->timestamp('starts_at')->nullable();
            $table->timestamp('ends_at')->nullable();
            $table->json('target_audience')->nullable(); // User segments
            $table->timestamps();

            $table->index('key');
            $table->index('is_active');
        });

        Schema::create('ab_test_assignments', function (Blueprint $table) {
            $table->id();
            $table->foreignId('ab_test_id')->constrained()->onDelete('cascade');
            $table->string('user_identifier', 191); // user_id or session_id
            $table->string('variant', 50); // 'A', 'B', etc.
            $table->timestamp('assigned_at');
            $table->timestamps();

            $table->unique(['ab_test_id', 'user_identifier']);
            $table->index(['ab_test_id', 'variant']);
        });

        Schema::create('ab_test_events', function (Blueprint $table) {
            $table->id();
            $table->foreignId('ab_test_id')->constrained()->onDelete('cascade');
            $table->string('user_identifier', 100);
            $table->string('variant', 50);
            $table->string('event_type', 50); // 'view', 'click', 'conversion', etc.
            $table->json('event_data')->nullable();
            $table->timestamp('occurred_at');
            $table->timestamps();

            $table->index(['ab_test_id', 'variant', 'event_type']);
            $table->index(['ab_test_id', 'occurred_at']);
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('ab_test_events');
        Schema::dropIfExists('ab_test_assignments');
        Schema::dropIfExists('ab_tests');
    }
};
