<?php
namespace Incoviba\Service\Venta;

use Incoviba\Common\Implement\Exception\EmptyResult;
use Incoviba\Repository;
use Incoviba\Model;
use Psr\Log\LoggerInterface;

class BonoPie
{
    public function __construct(protected Repository\Venta\BonoPie $bonoPieRepository,
                                protected LoggerInterface $logger,
                                protected Pago $pagoService) {}

    public function add(array $data): Model\Venta\BonoPie
    {
        $filteredData = $this->bonoPieRepository->filterData($data);
        if (!key_exists('pago', $filteredData)) {
            $pago = $this->pagoService->add($filteredData);
            $filteredData['pago'] = $pago->id;
        }
        try {
            $bono = $this->bonoPieRepository->fetchByPago($filteredData['pago']);
        } catch (EmptyResult) {
            $bono = $this->bonoPieRepository->create($filteredData);
            $bono = $this->bonoPieRepository->save($bono);
        }
        return $bono;
    }
    public function getByVenta(int $venta_id): Model\Venta\BonoPie
    {
        return $this->bonoPieRepository->fetchByVenta($venta_id);
    }
}
