<?php

declare(strict_types=1);

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class ArtworkAward extends Model
{
    protected $table = 'artwork_medals';

    protected $fillable = [
        'artwork_id',
        'user_id',
        'medal_type',
        'medal',
        'weight',
    ];

    protected $casts = [
        'artwork_id' => 'integer',
        'user_id'    => 'integer',
        'weight'     => 'integer',
    ];

    public const MEDALS = ['gold', 'silver', 'bronze'];

    public const WEIGHTS = [
        'gold'   => 5,
        'silver' => 3,
        'bronze' => 1,
    ];

    public static function weightFor(string $medal): int
    {
        return (int) config('artwork_medals.weights.' . $medal, self::WEIGHTS[$medal] ?? 0);
    }

    /**
     * @return array<string, int>
     */
    public static function weights(): array
    {
        return collect(self::MEDALS)
            ->mapWithKeys(fn (string $medal): array => [$medal => self::weightFor($medal)])
            ->all();
    }

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

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

    public function getMedalAttribute(): ?string
    {
        return $this->attributes['medal_type'] ?? null;
    }

    public function setMedalAttribute(?string $value): void
    {
        $this->attributes['medal_type'] = $value;
    }
}
