<?php

namespace App\Models;

use App\Enums\QuestionTypeEnum;
use App\Traits\QuestionTrait;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Cache;

class ContestQuestion extends Model
{
    use HasFactory, QuestionTrait;

    protected $fillable = [
        'contest_id',
        'explanation_type',
        'question_input_type',
        'time_limit',
        'order',
        'question_type',
        'options',
        'correct_answers',
        'score',
    ];

    protected $casts = [
        'correct_answers' => 'array',
        'options' => 'array',
        'score' => 'integer',
        'question_type' => QuestionTypeEnum::class,
    ];

    protected $appends = [
        'translation',
    ];

    public function translation(): Attribute
    {
        return new Attribute(
            get: function ($value) {
                $frontendLangCode = Cache::get('frontend_lang_code'.\request()->ip());
                $code = \request()->wantsJson() ? $frontendLangCode : app()->getLocale();

                $translation = $this->translations()->where('locale', $code)->first();

                return $translation ? $translation : $this->translations()->first();
            },
        );
    }

    public function answers(): \Illuminate\Database\Eloquent\Relations\HasMany
    {
        return $this->hasMany(ContestAnswer::class, 'contest_question_id');
    }

    public function translations(): \Illuminate\Database\Eloquent\Relations\MorphMany
    {
        return $this->morphMany(QuestionTranslation::class, 'questionable');
    }

    public function contest(): \Illuminate\Database\Eloquent\Relations\BelongsTo
    {
        return $this->belongsTo(Contest::class, 'contest_id');
    }
}
