<?php
namespace Incoviba\Service\Contabilidad\Movimiento;

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

class Detalle extends Ideal\Service
{
    public function __construct(LoggerInterface $logger,
                                protected Repository\Contabilidad\Movimiento\Detalle $detalleRepository,
                                protected Repository\Venta\Propietario               $propietarioRepository,
                                protected Repository\Inmobiliaria\Proveedor          $proveedorRepository,
                                protected Repository\Inmobiliaria                    $inmobiliariaRepository)
    {
        parent::__construct($logger);
    }

    public function getByMovimiento(int $movimiento_id): ?Model\Contabilidad\Movimiento\Detalle
    {
        try {
            return $this->process($this->detalleRepository->fetchByMovimiento($movimiento_id));
        } catch (Implement\Exception\EmptyResult) {
            return null;
        }
    }

    /**
     * @throws EmptyResult
     */
    public function findRut(int $rut): Define\Model
    {
        try {
            return $this->inmobiliariaRepository->fetchById($rut);
        } catch (Implement\Exception\EmptyResult) {}
        try {
            return $this->proveedorRepository->fetchById($rut);
        } catch (Implement\Exception\EmptyResult) {}
        try {
            return $this->propietarioRepository->fetchById($rut);
        } catch (Implement\Exception\EmptyResult) {}

        throw new Implement\Exception\EmptyResult("{$rut} no encontrado.");
    }

    protected function process(Model\Contabilidad\Movimiento\Detalle $detalle): Model\Contabilidad\Movimiento\Detalle
    {
        if (empty($detalle->rut)) {
            return $detalle;
        }

        try {
            $detalle->relacionado = $this->findRut($detalle->rut);
            $detalle->relacionadoType = strtolower(last(explode('\\', get_class($detalle->relacionado))));
        } catch (Implement\Exception\EmptyResult) {}

        return $detalle;
    }
}
