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

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

class Facturacion
{
    use withJson, withRedis, emptyBody;

    public function proyecto(ServerRequestInterface $request, ResponseInterface $response, Service\Redis $redisService,
                             Service\Venta $ventaService, int $proyecto_id): ResponseInterface
    {
        $output = [
            'proyecto_id' => $proyecto_id,
            'ventas' => []
        ];
        $today = new DateTimeImmutable();
        $redisKey = "ventas:facturacion:proyecto:{$proyecto_id}:{$today->format('Y-m-d')}";
        try {
            $output['ventas'] = $this->fetchRedis($redisService, $redisKey);
        } catch (EmptyRedis) {
            try {
                $output['ventas'] = $ventaService->getActivaByProyecto($proyecto_id);
                $this->saveRedis($redisService, $redisKey, $output['ventas']);
            } catch (EmptyResult) {}
        }
        return $this->withJson($response, $output);
    }
}
