<?php

declare(strict_types=1);

namespace Seka\Vzdelavanie\Models\Testovanie;

use Elceka\Laravel\HashId\Http\Traits\Hashidable;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Seka\Vzdelavanie\Enums\ModelStatusEnum;

/**
 * Class Otazka
 *
 * @package Seka\Vzdelavanie\Models\Testovanie
 */
class Otazka extends Model
{
    use Hashidable;
    use HasFactory;

    /**
     * @var string
     */
    protected $table = 'vzdelavanie_testovanie_otazky';

    /**
     * @var string[]
     */
    protected $fillable = [
        'id',
        'stav',
        'znenie',
        'druh_spravnej_odpovede',
    ];

    /**
     * @var string[]
     */
    protected $casts = [
        'stav' => ModelStatusEnum::class,
        'druh_spravnej_odpovede' => DruhSpravnejOdpovedeEnum::class,
    ];

    /**
     * @return void
     */
    protected static function boot(): void
    {
        parent::boot();

        static::deleting(function (Otazka $otazka) {
            $otazka->odpovede->each->delete();
        });
    }

    /**
     * @param \Illuminate\Database\Eloquent\Builder $query
     *
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopePublikovana(Builder $query): Builder
    {
        return $query->where('stav', ModelStatusEnum::PUBLIKOVANE);
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function test(): BelongsTo
    {
        return $this->belongsTo(Test::class, 'testovanie_testy_id', 'id');
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function odpovede(): HasMany
    {
        return $this->hasMany(Odpoved::class, 'testovanie_otazky_id', 'id');
    }

    /**
     * @return bool
     */
    public function spravneZodpovedana(): bool
    {
        $spravnychOdpovedi = $this->getAttribute('pocet_spravnych_odpovedi');

        return match ($this->getAttribute('druh_spravnej_odpovede')) {
            DruhSpravnejOdpovedeEnum::ZIADNA => $spravnychOdpovedi === 0,
            DruhSpravnejOdpovedeEnum::JEDNA, DruhSpravnejOdpovedeEnum::MINIMALNE_JEDNA => $spravnychOdpovedi >= 1,
            DruhSpravnejOdpovedeEnum::DVE => $spravnychOdpovedi === 2,
            DruhSpravnejOdpovedeEnum::TRI => $spravnychOdpovedi === 3,
        };
    }
}
