<?php
namespace Incoviba\Controller\API\Ventas;

use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\ResponseInterface;
use Incoviba\Common\Implement\Exception\EmptyResult;
use Incoviba\Controller\API\withJson;
use Incoviba\Controller\withRedis;
use Incoviba\Repository;
use Incoviba\Service;

class Comentarios
{
    use withJson, withRedis;

    public function edit(ServerRequestInterface $request, ResponseInterface $response,
                         Repository\Venta\Comentario $comentarioRepository,
                         Service\Redis $redisService, int $comentario_id): ResponseInterface
    {
        $output = [
            'comentario_id' => $comentario_id,
            'comentario' => null,
            'edited' => false
        ];
        $data = $request->getParsedBody();
        try {
            $comentario = $comentarioRepository->fetchById($comentario_id);
            $filteredData = $comentarioRepository->filterData($data);
            $comentario = $comentarioRepository->edit($comentario, $filteredData);

            $redisKey = "comentarios:venta:{$comentario->venta->id}";
            $comentarios = $this->fetchRedis($redisService, $redisKey);
            $index = array_column(json_decode(json_encode($comentarios), true), 'id');
            $idx = array_search($comentario->id, $index);
            $comentarios[$idx] = $comentario;
            $this->saveRedis($redisService, $redisKey, $comentarios);

            $output['comentario'] = $comentario;
            $output['edited'] = true;
        } catch (EmptyResult) {}
        return $this->withJson($response, $output);
    }
    public function remove(ServerRequestInterface $request, ResponseInterface $response,
                           Repository\Venta\Comentario $comentarioRepository, Service\Redis $redisService,
                           int $comentario_id): ResponseInterface
    {
        $output = [
            'comentario_id' => $comentario_id,
            'comentario' => null,
            'removed' => false
        ];
        try {
            $comentario = $comentarioRepository->fetchById($comentario_id);
            $output['comentario'] = $comentario;
            $comentarioRepository->remove($comentario);

            $redisKey = "comentarios:venta:{$comentario->venta->id}";
            $comentarios = $this->fetchRedis($redisService, $redisKey);
            $index = array_column(json_decode(json_encode($comentarios), true), 'id');
            $idx = array_search($comentario->id, $index);
            unset($comentarios[$idx]);
            $this->saveRedis($redisService, $redisKey, $comentarios);

            $output['removed'] = true;
        } catch (EmptyResult) {}
        return $this->withJson($response, $output);
    }
}
