<?php

declare(strict_types=1);

namespace Seka\Portal\Modul\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\HasMany;
use Illuminate\Database\Eloquent\Relations\MorphMany;
use Seka\Portal\Modul\Vzdelavanie\Enums\ModelStatusEnum;
use Seka\Portal\Modul\Vzdelavanie\Enums\ModelsTypeEnum;
use Seka\Portal\Modul\Vzdelavanie\Models\Popularita\Popularita;

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

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

    /**
     * @var string[]
     */
    protected $fillable = [
        'id',
        'nazov',
        'popis',
        'pocet_otazok',
        'stav',
    ];

    /**
     * @var string[]
     */
    protected $appends = [
        'popularita_count',
    ];

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

    /**
     * @return string
     */
    public static function type(): string
    {
        return ModelsTypeEnum::MODEL_TYPE_TESTOVANIE_TEST->value;
    }

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

        static::deleting(function (Test $test) {
            $test->otazky->each->delete();
            $test->popularita->each->delete();
        });
    }

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

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

    /**
     * @return int
     */
    public function getPopularitaCountAttribute(): int
    {
        return $this->popularita()->count();
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\MorphMany
     */
    public function popularita(): MorphMany
    {
        return $this->morphMany(Popularita::class, 'popularita');
    }
}
