<?php

namespace App\Models;

use App\Enums\DifficultyLevelEnums;
use App\Enums\QuizStatusEnum;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Cache;

class Quiz extends Model
{
    use HasFactory;

    protected $fillable = [
        'quiz_level',
        'category_id',
        'image',
        'has_level',
        'point_to_pass', // points required to pass the quiz
        'banner_image',
        'is_free',
        'status',
    ];

    protected $casts = [
        'has_level' => 'boolean',
        'is_free' => 'boolean',
        'tags' => 'array',
        'status' => QuizStatusEnum::class,
        'quiz_level' => DifficultyLevelEnums::class,
    ];

    protected $appends = [
        'translation',
        'quiz_level_name',
        'status_name',
    ];

    public function getQuizLevelNameAttribute(): string
    {
        return $this->quiz_level ? $this->quiz_level->label() : '';
    }

    public function getStatusNameAttribute(): string
    {
        return $this->status ? $this->status->label() : '';
    }

    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 scopeActive($query)
    {
        return $query->where('status', QuizStatusEnum::ACTIVE);
    }

    public function scopeInactive($query)
    {
        return $query->where('status', QuizStatusEnum::INACTIVE);
    }

    public function translations()
    {
        return $this->hasMany(QuizTranslation::class, 'quiz_id');
    }

    public function scopeIsActive($query)
    {
        return $query->where('status', QuizStatusEnum::ACTIVE);
    }

    public function category()
    {
        return $this->belongsTo(QuizCategory::class, 'category_id');
    }

    public function questionLevels()
    {
        return $this->hasMany(QuestionLevel::class, 'quiz_id');
    }

    public function levels()
    {
        return $this->belongsToMany(Level::class, 'question_levels', 'quiz_id', 'level_id');
    }

    public function questions()
    {
        return $this->hasMany(QuizQuestion::class, 'quiz_id');
    }

    public function userQuizzes()
    {
        return $this->hasMany(UserQuiz::class, 'quiz_id');
    }

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

    public function favorites()
    {
        return $this->morphMany(Favorite::class, 'favorable');
    }

    public function getSearchAttribute()
    {
        return [
            'quiz_level',
            'status',
            'translations.title',
            'translations.description',
        ];
    }

    public function isCompletedByUser(UserQuiz $userQuiz, $levelId = null): bool
    {
        $totalQuestions = $this->questions()->where('question_level_id', $levelId)->count();
        $totalAnswers = $userQuiz->answers()->where('question_level_id', $levelId)->count();

        if ($totalQuestions === $totalAnswers) {
            return true;
        }

        return false;
    }
}
