<?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('notification_deliveries', function (Blueprint $table) {
            $table->id();
            $table->foreignId('notification_id')->constrained()->onDelete('cascade');
            $table->foreignId('user_id')->constrained()->onDelete('cascade');
            $table->string('device_token')->nullable(); // Firebase device token
            $table->timestamp('delivered_at')->nullable();
            $table->timestamp('opened_at')->nullable();
            $table->timestamp('clicked_at')->nullable();
            $table->enum('status', ['pending', 'delivered', 'opened', 'clicked', 'failed'])->default('pending');
            $table->text('error_message')->nullable();
            $table->json('delivery_metadata')->nullable(); // Additional delivery info
            $table->timestamps();
            
            // Unique constraint to prevent duplicate deliveries to same user
            $table->unique(['notification_id', 'user_id']);
            
            // Indexes for performance
            $table->index(['notification_id', 'status']);
            $table->index(['user_id', 'status']);
            $table->index(['status', 'delivered_at']);
        });
    }

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