<?php

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

use App\Dtos\InformaciaDto;
use App\Dtos\PouzivatelDto;
use App\Http\Controllers\API\V1\Pouzivatel\PouzivatelDtoTransformer;
use App\Models\Informacia\Informacia;
use App\Repositories\HodnotenieRepositoryContract;
use App\Repositories\PouzivatelRepositoryContract;
use PHPOpenSourceSaver\Fractal\Resource\ResourceAbstract;
use PHPOpenSourceSaver\Fractal\TransformerAbstract;

/**
 * Class InformaciaTransformer
 */
class InformaciaTransformer extends TransformerAbstract
{
    /**
     * @var string[]
     */
    protected array $availableIncludes = [
        'hodnotenia',
        'vytvoril',
    ];

    /**
     * @var string[]
     */
    protected array $defaultIncludes = [];

    public function transform(Informacia $informacia): array
    {
        $informaciaDto = InformaciaDto::from($informacia)->only(
            'id',
            'titulok',
            'uvod',
            'obsah',
            'stav',
            'cas_zverejnenia',
            'odporucane',
            'hash_id',
        );

        return array_merge(
            $informaciaDto->toArray(),
            [
                'links' => [
                    'self' => route(
                        'app.api.frontend.informacie.get',
                        [
                            'informaciaHashId' => $informacia->hashId(),
                        ],
                    ),
                ],
            ],
        );
    }

    public function includeHodnotenia(Informacia $informacia): ResourceAbstract
    {
        $hodnotenieRepository = app(HodnotenieRepositoryContract::class);
        $hodnoteniePouzivatela = $hodnotenieRepository->hodnoteniePouzivatela(auth()->user(), $informacia);

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

        return $this->item(
            $sumar,
            new SumarHodnoteniaDtoTransformer,
            'hodnotenie',
        );
    }

    public function includeVytvoril(Informacia $informacia): ResourceAbstract
    {
        $pouzivatelRepository = app(PouzivatelRepositoryContract::class);
        $pouzivatel = $pouzivatelRepository->find($informacia->vytvoril_id);

        $pouzivatelDto = PouzivatelDto::from($pouzivatel)
            ->only(
                'id',
                'meno',
                'priezvisko',
                'cele_meno',
            );

        return $this->item(
            $pouzivatelDto,
            new PouzivatelDtoTransformer,
            'vytvoril',
        );
    }
}
