<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
use Spatie\Activitylog\Traits\LogsActivity;
use Spatie\Activitylog\LogOptions;

class ElectionCandidate extends Model
{
    use HasFactory, LogsActivity;

    // =========================================================================
    // Constants
    // =========================================================================

    public const STATUS_PENDING = 'pending';
    public const STATUS_APPROVED = 'approved';
    public const STATUS_REJECTED = 'rejected';
    public const STATUS_WITHDRAWN = 'withdrawn';
    public const STATUS_DISQUALIFIED = 'disqualified';

    public const STATUSES = [
        self::STATUS_PENDING => 'Pending Review',
        self::STATUS_APPROVED => 'Approved',
        self::STATUS_REJECTED => 'Rejected',
        self::STATUS_WITHDRAWN => 'Withdrawn',
        self::STATUS_DISQUALIFIED => 'Disqualified',
    ];

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

    protected $fillable = [
        'uuid',
        'election_id',
        'position_id',
        'association_id',
        'user_id',
        'nominated_by',
        'status',
        'manifesto',
        'photo_path',
        'campaign_slogan',
        'qualifications',
        'rejection_reason',
        'reviewed_by',
        'reviewed_at',
        'withdrawn_at',
        'endorsement_count',
        'metadata',
    ];

    protected $casts = [
        'qualifications' => 'json',
        'metadata' => 'json',
        'reviewed_at' => 'datetime',
        'withdrawn_at' => 'datetime',
        'endorsement_count' => 'integer',
    ];

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

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

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

    // =========================================================================
    // Activity Logging
    // =========================================================================

    public function getActivitylogOptions(): LogOptions
    {
        return LogOptions::defaults()
            ->logOnly(['status', 'rejection_reason'])
            ->setDescriptionForEvent(fn (string $eventName) => "Election candidate {$eventName}")
            ->useLogName('elections')
            ->logOnlyDirty();
    }

    // =========================================================================
    // 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 user()
    {
        return $this->belongsTo(User::class);
    }

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

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

    public function endorsements()
    {
        return $this->hasMany(ElectionEndorsement::class, 'candidate_id');
    }

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

    public function scopeApproved($query)
    {
        return $query->where('status', self::STATUS_APPROVED);
    }

    public function scopePending($query)
    {
        return $query->where('status', self::STATUS_PENDING);
    }

    // =========================================================================
    // Accessors
    // =========================================================================

    public function getPhotoUrlAttribute(): ?string
    {
        return $this->photo_path ? asset('storage/' . $this->photo_path) : null;
    }

    public function getStatusLabelAttribute(): string
    {
        return self::STATUSES[$this->status] ?? ucfirst($this->status);
    }
}
