<?php

namespace App\Models;

use App\Enums\ModerationStatus;
use App\Enums\ProfileVisibility;
use App\Enums\RecordType;
use App\Support\PublicId;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;

class PlayerRecord extends Model
{
    use SoftDeletes;

    protected $fillable = [
        'public_id',
        'player_profile_id',
        'player_game_profile_id',
        'game_id',
        'title',
        'description',
        'record_type',
        'achievement_date',
        'result_text',
        'rank_id',
        'visibility',
        'moderation_status',
        'moderation_reason',
        'published_at',
    ];

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

    protected function casts(): array
    {
        return [
            'record_type' => RecordType::class,
            'achievement_date' => 'date',
            'visibility' => ProfileVisibility::class,
            'moderation_status' => ModerationStatus::class,
            'published_at' => 'datetime',
        ];
    }

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

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

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

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

    public function rank(): BelongsTo
    {
        return $this->belongsTo(GameRank::class, 'rank_id');
    }

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