<?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_votes', function (Blueprint $table) {
            $table->id();
            $table->uuid('uuid')->unique();
            $table->foreignId('election_id')->constrained('elections')->cascadeOnDelete();
            $table->foreignId('position_id')->constrained('election_positions')->cascadeOnDelete();
            $table->foreignId('association_id')->constrained()->cascadeOnDelete();

            // For non-anonymous: direct voter reference. For anonymous: NULL
            $table->foreignId('voter_id')->nullable()->constrained('users')->nullOnDelete();

            // For anonymous: hash of the burned token
            $table->string('vote_token_hash', 64)->nullable();

            // Vote payload (strategy-specific JSON)
            // Plurality:    {"candidate_id": 5}
            // RankedChoice: {"rankings": [{"candidate_id":5,"rank":1}, ...]}
            // Approval:     {"candidate_ids": [5, 3, 7]}
            // Weighted:     {"weights": [{"candidate_id":5,"weight":60}, ...]}
            // Referendum:   {"choice": "yes"}
            $table->json('vote_data');

            // Integrity
            $table->string('vote_hash', 64); // SHA-256
            $table->string('salt', 64);      // Random salt for hash

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

            // Invalidation
            $table->boolean('is_invalidated')->default(false);
            $table->string('invalidation_reason')->nullable();
            $table->foreignId('invalidated_by')->nullable()->constrained('users')->nullOnDelete();

            $table->timestamps();

            $table->index(['election_id', 'position_id']);
            $table->index(['election_id', 'voter_id']);
            $table->index('vote_hash');
            $table->index('vote_token_hash');
        });
    }

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