<?php

namespace App\Models;

use App\Enums\PaymentStatus;
use App\Enums\RegistrationStatus;
use App\Support\PublicId;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

class EventRegistration extends Model
{
    protected $fillable = [
        'public_id',
        'event_id',
        'user_id',
        'player_profile_id',
        'player_game_profile_id',
        'status',
        'payment_status',
        'contact_name',
        'contact_email',
        'contact_phone_e164',
        'contact_whatsapp',
        'admin_notes',
        'user_notes',
        'registered_at',
        'confirmed_at',
        'cancelled_at',
        'reviewed_by',
        'reviewed_at',
        'waitlist_position',
    ];

    public function getRouteKeyName(): string
    {
        return 'public_id';
    }

    protected function casts(): array
    {
        return [
            'status' => RegistrationStatus::class,
            'payment_status' => PaymentStatus::class,
            'contact_whatsapp' => 'boolean',
            'registered_at' => 'datetime',
            'confirmed_at' => 'datetime',
            'cancelled_at' => 'datetime',
            'reviewed_at' => 'datetime',
            'waitlist_position' => 'integer',
        ];
    }

    protected static function booted(): void
    {
        static::creating(function (EventRegistration $registration): void {
            if (empty($registration->public_id)) {
                $registration->public_id = PublicId::generate();
            }
        });
    }

    public function event(): BelongsTo
    {
        return $this->belongsTo(Event::class);
    }

    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }

    public function playerProfile(): BelongsTo
    {
        return $this->belongsTo(PlayerProfile::class);
    }

    public function playerGameProfile(): BelongsTo
    {
        return $this->belongsTo(PlayerGameProfile::class);
    }

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

    public function statusEvents(): HasMany
    {
        return $this->hasMany(EventRegistrationStatusEvent::class);
    }

    public function paymentProofs(): HasMany
    {
        return $this->hasMany(EventPaymentProof::class);
    }
}
