<?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
 */
final class OhodnotInformaciuAction extends BaseController
{
    private HodnotenieRepositoryContract $hodnotenieRepository;

    private InformaciaRepositoryContract $informaciaRepository;

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

    /**
     * @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 = SumarHodnoteniDto::from(
                [
                    '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ť.');
        }
    }
}
