<?php

namespace App\Http\Controllers\API\V1\Informacia\Frontend;

use App\Http\Controllers\API\BaseController;
use App\Http\Requests\HodnotenieZaznamuRequest;
use App\Repositories\HodnotenieRepositoryContract;
use App\Repositories\InformaciaRepositoryContract;
use Exception;
use Illuminate\Http\Response;

/**
 * Class OhodnotInformaciuAction
 *
 * @package App\Http\Controllers\API\V1\Informacia\Frontend
 */
final class OhodnotInformaciuAction extends BaseController
{
    /**
     * @var HodnotenieRepositoryContract
     */
    private HodnotenieRepositoryContract $hodnotenieRepository;
    /**
     * @var InformaciaRepositoryContract
     */
    private InformaciaRepositoryContract $informaciaRepository;

    /**
     * @param InformaciaRepositoryContract $informaciaRepository
     * @param HodnotenieRepositoryContract $hodnotenieRepository
     */
    public function __construct(
        InformaciaRepositoryContract $informaciaRepository,
        HodnotenieRepositoryContract $hodnotenieRepository
    ) {
        $this->informaciaRepository = $informaciaRepository;
        $this->hodnotenieRepository = $hodnotenieRepository;
    }

    /**
     * @param int $informaciaId
     * @param HodnotenieZaznamuRequest $request
     * @return Response|void
     * @throws Exception
     */
    public function __invoke(int $informaciaId, HodnotenieZaznamuRequest $request): Response
    {
        try {
            $pouzivatel = auth()->user();
            $informacia = $this->informaciaRepository->find($informaciaId);
            $this->hodnotenieRepository->ohodnot($pouzivatel, $informacia, $request->get('hodnotenie'));
            $informacia->refresh();
            $hodnoteniePouzivatela = $this->hodnotenieRepository->hodnoteniePouzivatela(auth()->user(), $informacia);

            $sumar = new SumarHodnoteniDto(
                [
                    'id' => $informacia->id,
                    'pocetKladnychHodnoteni' => $informacia->pocetKladnychHodnoteni,
                    'pocetZapornychHodnoteni' => $informacia->pocetZapornychHodnoteni,
                    'pocetVsetkychHodnoteni' => $informacia->pocetVsetkychHodnoteni,
                    'hodnoteniePouzivatela' => $hodnoteniePouzivatela,
                ],
            );

            return $this->response->item($sumar);
        } catch (Exception $e) {
            $this->response->errorInternal('Informáciu sa nepodarilo ohodnotiť.');
        }
    }
}
