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

use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\ResponseInterface;
use Incoviba\Controller\API\{withJson, emptyBody};
use Incoviba\Controller\withRedis;
use Incoviba\Common\Implement\Exception\EmptyResult;
use Incoviba\Exception\ServiceAction\{Create, Read, Update};
use Incoviba\Service;

class Pies
{
    use withRedis, withJson, emptyBody;

    public function edit(ServerRequestInterface $request, ResponseInterface $response, Service\Venta\Pie $pieService, int $pie_id): ResponseInterface
    {
        $body = $request->getParsedBody();
        $output = [
            'pie_id' => $pie_id,
            'input' => $body,
            'edited' => false
        ];
        try {
            $pie = $pieService->getById($pie_id);
            $pieService->edit($pie, (array) $body);
            $output['edited'] = true;
        } catch (EmptyResult) {}
        return $this->withJson($response, $output);
    }
    public function add(ServerRequestInterface $request, ResponseInterface $response, Service\Venta $ventaService,
                        Service\Venta\Pie $pieService, int $venta_id): ResponseInterface
    {
        $input = $request->getParsedBody();
        $output = [
            'venta_id' => $venta_id,
            'input' => $input,
            'pie' => null,
            'success' => false
        ];
        try {
            $venta = $ventaService->getById($venta_id);

        } catch (Read $exception) {
            return $this->withError($response, $exception);
        }
        try {
            $pie = $pieService->add($input);
        } catch (Create $exception) {
            return $this->withError($response, $exception);
        }
        try {
            $ventaService->edit($venta, ['pie' => $pie->id]);

            $output['pie'] = $pie;
            $output['success'] = true;
        } catch (Update $exception) {
            return $this->withError($response, $exception);
        }
        return $this->withJson($response, $output);
    }
}
