<?php

declare(strict_types=1);

namespace Seka\Terminy\Actions;

use App\Models\Pouzivatel\Pouzivatel;
use App\Models\Pracovisko\Pracovisko;
use Seka\Terminy\Models\Udalost\Udalost;
use Seka\Terminy\Exceptions\UdalostSaUzKonala;
use Seka\Terminy\Exceptions\UdalostUzPrebieha;
use Seka\Terminy\Models\Registracia\Registracia;
use Seka\Terminy\Exceptions\UdalostNemaVolnuKapacitu;
use Seka\Terminy\Exceptions\NaUdalostNieJePovolenaRegistracia;
use Seka\Terminy\Exceptions\ExistujeRegistraciaPouzivatelaNaUdalost;

/**
 * Class CreateRegistration
 *
 * @package Seka\Terminy\Actions
 */
final class CreateRegistration
{
    /**
     * @param \Seka\Terminy\Models\Udalost\Udalost         $udalost
     * @param \App\Models\Pouzivatel\Pouzivatel            $registroval
     * @param \App\Models\Pracovisko\Pracovisko            $pracovisko
     * @param \Seka\Terminy\Models\Registracia\Registracia $registracia
     *
     * @throws \Seka\Terminy\Exceptions\ExistujeRegistraciaPouzivatelaNaUdalost
     * @throws \Seka\Terminy\Exceptions\NaUdalostNieJePovolenaRegistracia
     * @throws \Seka\Terminy\Exceptions\UdalostNemaVolnuKapacitu
     * @throws \Seka\Terminy\Exceptions\UdalostSaUzKonala
     * @throws \Seka\Terminy\Exceptions\UdalostUzPrebieha
     * @throws \Throwable
     */
    public static function execute(Udalost $udalost, Pouzivatel $registroval, Pracovisko $pracovisko, Registracia $registracia): void
    {
        if (false === $udalost->jePovolenaRegistracia()) {
            throw new NaUdalostNieJePovolenaRegistracia();
        }

        if ($udalost->skoncila) {
            throw new UdalostSaUzKonala();
        }

        if (true === $udalost->prebieha) {
            throw new UdalostUzPrebieha();
        }

        if (false === $udalost->ma_volnu_kapacitu) {
            throw new UdalostNemaVolnuKapacitu();
        }

        // ak nebol zvoleny existujuci pouzivatel a registracie na udalost maju zvoleneho existujuceho pouzivatela
        if (!is_null($registracia->pouzivatel_id) && $udalost->registracie()->has('pouzivatel')) {
            if (false === is_null($udalost->registracie()->wherePouzivatelId($registracia->pouzivatel_id)->first())) {
                throw new ExistujeRegistraciaPouzivatelaNaUdalost();
            }
        }

        $registracia->udalost()->associate($udalost);
        $registracia->vytvoril()->associate($registroval);
        $registracia->pracovisko()->associate($pracovisko);

        $registracia->saveOrFail();
    }
}
