<?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('election_voters', function (Blueprint $table) {
            $table->id();
            $table->foreignId('election_id')->constrained('elections')->cascadeOnDelete();
            $table->foreignId('user_id')->constrained('users')->cascadeOnDelete();
            $table->foreignId('association_id')->constrained()->cascadeOnDelete();

            // Eligibility
            $table->boolean('is_eligible')->default(true);
            $table->string('ineligibility_reason')->nullable();

            // Voting status
            $table->boolean('has_voted')->default(false);
            $table->dateTime('voted_at')->nullable();

            // Anonymous voting token
            $table->string('vote_token_hash', 64)->nullable();
            $table->boolean('token_used')->default(false);

            // Physical voting
            $table->boolean('voted_physically')->default(false);
            $table->foreignId('physical_vote_recorded_by')->nullable()->constrained('users')->nullOnDelete();

            // OTP verification
            $table->string('otp_code', 10)->nullable();
            $table->dateTime('otp_expires_at')->nullable();
            $table->boolean('otp_verified')->default(false);

            // Device/IP tracking
            $table->string('ip_address', 45)->nullable();
            $table->text('user_agent')->nullable();
            $table->string('device_fingerprint')->nullable();

            $table->timestamps();

            $table->unique(['election_id', 'user_id']);
            $table->index(['election_id', 'is_eligible']);
            $table->index(['election_id', 'has_voted']);
            $table->index('vote_token_hash');
        });
    }

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