<?php
namespace Incoviba\Service;

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

class Sociedad extends Ideal\Service
{
    public function __construct(LoggerInterface $logger, protected Repository\Sociedad $sociedadRepository,
                                protected Repository\Inmobiliaria $inmobiliariaRepository,
                                protected Repository\Inmobiliaria\Proveedor $proveedorRepository)
    {
        parent::__construct($logger);
    }

    public function getByRut(int $sociedad_rut): ?Model\Sociedad
    {
        try {
            return $this->process($this->sociedadRepository->fetchById($sociedad_rut));
        } catch (EmptyResult) {
            return null;
        }
    }
    public function getAll(?string $orderBy = null): array
    {
        try {
            return array_map([$this, 'process'], $this->sociedadRepository->fetchAll($orderBy));
        } catch (EmptyResult) {
            return [];
        }
    }
    public function add(array $data): ?Model\Sociedad
    {
        try {
            return $this->process($this->sociedadRepository->fetchById($data['rut']));
        } catch (EmptyResult) {
            try {
                return $this->process($this->sociedadRepository->save($this->sociedadRepository->create($data)));
            } catch (PDOException) {
                return null;
            }
        }
    }
    public function edit(int $sociedad_rut, array $data): ?Model\Sociedad
    {
        try {
            return $this->process(
                $this->sociedadRepository->edit(
                    $this->sociedadRepository->fetchById($sociedad_rut), $data));
        } catch (EmptyResult) {
            return null;
        }
    }
    public function delete(int $sociedad_rut): bool
    {
        try {
            $this->sociedadRepository->remove($this->sociedadRepository->fetchById($sociedad_rut));
            return true;
        } catch (EmptyResult) {
            return false;
        }
    }
    public function asignar(int $inmobiliaria_rut, int $sociedad_rut): ?Model\Inmobiliaria\Proveedor
    {
        try {
            $inmobiliaria = $this->inmobiliariaRepository->fetchById($inmobiliaria_rut);
            $sociedad = $this->sociedadRepository->fetchById($sociedad_rut);
            $data = [
                'inmobiliaria_rut' => $inmobiliaria->rut,
                'sociedad_rut' => $sociedad->rut,
            ];
            return $this->proveedorRepository->save($this->proveedorRepository->create($data));
        } catch (EmptyResult) {
            return null;
        }
    }

    protected function process(Model\Sociedad $sociedad): Model\Sociedad
    {
        return $sociedad;
    }
}
