<?php

declare(strict_types=1);

namespace Seka\Vzdelavanie\Models\Testovanie;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;
use Seka\Vzdelavanie\Enums\ModelsTypeEnum;
use Seka\Vzdelavanie\Enums\ModelStatusEnum;
use Elceka\Laravel\HashId\Http\Traits\Hashidable;
use Seka\Vzdelavanie\Models\Popularita\Popularita;
use Illuminate\Database\Eloquent\Relations\MorphMany;

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

    /**
     * @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,
    ];

    /**
     *
     */
    protected static function boot()
    {
        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)
    {
        return $query->where('stav', ModelStatusEnum::PUBLIKOVANE());
    }

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

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

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

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