<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;

class ElectionVote extends Model
{
    use HasFactory;

    // =========================================================================
    // Model Configuration
    // =========================================================================

    protected $fillable = [
        'uuid',
        'election_id',
        'position_id',
        'association_id',
        'voter_id',
        'vote_token_hash',
        'vote_data',
        'vote_hash',
        'salt',
        'ip_address',
        'user_agent',
        'device_fingerprint',
        'is_invalidated',
        'invalidation_reason',
        'invalidated_by',
    ];

    protected $casts = [
        'vote_data' => 'json',
        'is_invalidated' => 'boolean',
    ];

    // =========================================================================
    // Boot
    // =========================================================================

    protected static function boot()
    {
        parent::boot();

        static::creating(function (ElectionVote $vote) {
            if (!$vote->uuid) {
                $vote->uuid = (string) Str::uuid();
            }
        });
    }

    // =========================================================================
    // Relationships
    // =========================================================================

    public function election()
    {
        return $this->belongsTo(Election::class);
    }

    public function position()
    {
        return $this->belongsTo(ElectionPosition::class, 'position_id');
    }

    public function association()
    {
        return $this->belongsTo(Association::class);
    }

    public function voter()
    {
        return $this->belongsTo(User::class, 'voter_id');
    }

    public function invalidator()
    {
        return $this->belongsTo(User::class, 'invalidated_by');
    }

    // =========================================================================
    // Scopes
    // =========================================================================

    public function scopeValid($query)
    {
        return $query->where('is_invalidated', false);
    }

    public function scopeInvalidated($query)
    {
        return $query->where('is_invalidated', true);
    }

    public function scopeAnonymous($query)
    {
        return $query->whereNull('voter_id')->whereNotNull('vote_token_hash');
    }

    // =========================================================================
    // Helpers
    // =========================================================================

    public function isAnonymous(): bool
    {
        return is_null($this->voter_id) && !is_null($this->vote_token_hash);
    }
}
