<?php
namespace Incoviba\Service\Venta;

use Exception;
use DateTimeImmutable;
use Incoviba\Common\Implement\Exception\EmptyResult;
use Incoviba\Exception\ServiceAction\Read;
use Psr\Log\LoggerInterface;
use Incoviba\Common\Ideal;
use Incoviba\Repository;
use Incoviba\Model;
use Incoviba\Service;

class Credito extends Ideal\Service
{
    public function __construct(
        LoggerInterface $logger,
        protected Repository\Venta\Credito $creditoRepository,
        protected Pago $pagoService,
        protected Repository\Venta\TipoPago $tipoPagoRepository,
        protected Repository\Venta\EstadoPago $estadoPagoRepository,
        protected Repository\Venta\TipoEstadoPago $tipoEstadoPagoRepository,
        protected Service\Money $moneyService,
        protected Service\Valor $valorService
    ) {
        parent::__construct($logger);
    }

    /**
     * @param int $venta_id
     * @return Model\Venta\Credito
     * @throws Read
     */
    public function getByVenta(int $venta_id): Model\Venta\Credito
    {
        try {
            return $this->creditoRepository->fetchByVenta($venta_id);
        } catch (EmptyResult $exception) {
            throw new Read(__CLASS__, $exception);
        }
    }

    /**
     * @throws Exception
     */
    public function add(array $data): Model\Venta\Credito
    {
        $fecha = new DateTimeImmutable($data['fecha']);
        $uf = $this->valorService->clean($data['uf']) ?? $this->moneyService->getUF($fecha);
        $tipoPago = $this->tipoPagoRepository->fetchByDescripcion('carta de resguardo');
        $valor = $this->valorService->clean($data['valor']);
        $pago = $this->pagoService->add([
            'fecha' => $fecha->format('Y-m-d'),
            'valor' => round($valor * $uf),
            'uf' => $uf,
            'tipo' => $tipoPago->id
        ]);
        $credito = $this->creditoRepository->create([
            'valor' => $valor,
            'fecha' => $fecha->format('Y-m-d'),
            'pago' => $pago->id
        ]);
        return $this->creditoRepository->save($credito);
    }

    /**
     * @throws Exception
     */
    public function edit(Model\Venta\Credito $credito, array $data): Model\Venta\Credito
    {
        $uf = $this->moneyService->getUF($credito->pago->fecha);
        if (array_key_exists('fecha', $data)) {
            $fecha = new DateTimeImmutable($data['fecha']);
            $data['fecha'] = $fecha->format('Y-m-d');
            $uf = $this->moneyService->getUF($fecha);
            $data['uf'] = $uf;
        }
        if (array_key_exists('valor', $data)) {
            $data['valor'] = $this->valorService->clean($data['valor']);
            $valorPago = round($data['valor'] * $uf);
        }
        $filteredData = array_intersect_key($data, array_flip([
            'fecha',
            'uf',
            'valor',
            'banco'
        ]));
        $filteredDataPago = $filteredData;
        if (isset($valorPago)) {
            $filteredDataPago['valor'] = $valorPago;
        }
        $credito->pago = $this->pagoService->edit($credito->pago, $filteredDataPago);

        return $this->creditoRepository->edit($credito, $filteredData);
    }
}
