<?php

namespace App\Models;

use App\Enums\QuestionInputTypeEnum;
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 QuizQuestion extends Model
{
    use HasFactory, QuestionTrait;

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

    protected $casts = [
        'correct_answers' => 'array',
        'options' => 'array',
        'score' => 'integer',
        'question_type' => QuestionTypeEnum::class,
        'question_input_type' => QuestionInputTypeEnum::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 translations(): \Illuminate\Database\Eloquent\Relations\MorphMany
    {
        return $this->morphMany(QuestionTranslation::class, 'questionable');
    }

    public function quiz()
    {
        return $this->belongsTo(Quiz::class, 'quiz_id');
    }

    public function questionLevel()
    {
        return $this->belongsTo(QuestionLevel::class, 'question_level_id');
    }

    public function answers()
    {
        return $this->hasMany(QuizAnswer::class, 'question_id');
    }

    public function getSearchAttribute()
    {
        return [
            'question_text',
            'question_type',
        ];
    }
}
