<?php

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

/**
 * Migration: Digital Health Advocacy - Poll Responses Table
 * 
 * Stores individual poll responses from users and guests.
 * Supports both registered users and anonymous voting with tracking.
 * 
 * @author SSHIA Development Team
 * @version 1.0.0
 */
return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('r_poll_responses', function (Blueprint $table) {
            // Primary Key
            $table->id();
            
            // Foreign Key to Poll
            $table->foreignId('poll_id')
                  ->constrained('r_polls')
                  ->onDelete('cascade')
                  ->comment('Associated poll');
            
            // Foreign Key to Option
            $table->foreignId('option_id')
                  ->constrained('r_poll_options')
                  ->onDelete('cascade')
                  ->comment('Selected option');
            
            // Respondent (for registered users)
            $table->foreignId('user_id')
                  ->nullable()
                  ->constrained('users')
                  ->nullOnDelete()
                  ->comment('Registered user (null for anonymous)');
            
            // Guest Tracking (hash to prevent duplicate votes)
            $table->string('respondent_hash', 64)
                  ->nullable()
                  ->comment('Hash for guest tracking (IP + User Agent)');
            
            // Custom "Other" Response
            $table->string('other_text', 500)
                  ->nullable()
                  ->comment('Custom text for "other" option');
            
            // Metadata
            $table->string('ip_address', 45)
                  ->nullable()
                  ->comment('IP address for fraud detection');
            
            $table->text('user_agent')
                  ->nullable()
                  ->comment('Browser user agent');
            
            // Timestamps
            $table->timestamps();
            
            // Indexes
            $table->index('poll_id');
            $table->index('option_id');
            $table->index('user_id');
            $table->index('respondent_hash');
            $table->unique(['poll_id', 'user_id'], 'r_poll_responses_user_poll_unique');
            $table->index(['poll_id', 'respondent_hash'], 'r_poll_responses_guest_poll_index');
        });
    }

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