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

            // Common fields
            $table->string('device_id');
            $table->text('user_agent')->nullable();
            $table->string('ip_address')->nullable();
            $table->enum('platform', ['web', 'ios', 'android'])->default('web');

            // Export-specific fields
            $table->unsignedBigInteger('meme_id')->nullable();
            $table->unsignedBigInteger('meme_media_id')->nullable();
            $table->unsignedBigInteger('background_media_id')->nullable();
            $table->json('caption_texts');
            $table->enum('export_status', ['initiated', 'processing', 'completed', 'failed'])->default('initiated');
            $table->text('error_message')->nullable();

            // Timestamps
            $table->timestamp('action_at');
            $table->timestamp('completed_at')->nullable();
            $table->timestamps();

            // Foreign key constraints
            $table->foreign('meme_id')->references('id')->on('memes')->onDelete('set null');
            $table->foreign('meme_media_id')->references('id')->on('meme_medias')->onDelete('set null');
            $table->foreign('background_media_id')->references('id')->on('background_medias')->onDelete('set null');

            // Indexes
            $table->index(['device_id', 'action_at']);
            $table->index(['export_status', 'action_at']);
            $table->index('platform');
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('tracking_exports');
    }
};
