<?php
namespace Incoviba\Service\Venta;

use Incoviba\Controller\API\Ventas\Promotions;
use PDOException;
use Psr\Log\LoggerInterface;
use Incoviba\Common\Ideal;
use Incoviba\Common\Implement;
use Incoviba\Exception;
use Incoviba\Model;
use Incoviba\Repository;
use Incoviba\Service;

class Promotion extends Ideal\Service
{
    public function __construct(LoggerInterface $logger,
                                protected Repository\Venta\Promotion $promotionRepository,
                                protected Repository\Proyecto $projectRepository,
                                protected Repository\Proyecto\Broker\Contract $contractRepository,
                                protected Repository\Proyecto\Broker $brokerRepository,
                                protected Repository\Proyecto\TipoUnidad $tipoUnidadRepository,
                                protected Repository\Proyecto\ProyectoTipoUnidad $proyectoTipoUnidadRepository,
                                protected Repository\Venta\Unidad $unidadRepository)
    {
        parent::__construct($logger);
    }

    public function getAll(null|string|array $order = null): array
    {
        try {
            return array_map([$this, 'process'], $this->promotionRepository->fetchAll($order));
        } catch (Implement\Exception\EmptyResult) {
            return [];
        }
    }

    /**
     * @param int $promotion_id
     * @return Model\Venta\Promotion
     * @throws Exception\ServiceAction\Read
     */
    public function getById(int $promotion_id): Model\Venta\Promotion
    {
        try {
            return $this->process($this->promotionRepository->fetchById($promotion_id));
        } catch (Implement\Exception\EmptyResult $exception) {
            throw new Exception\ServiceAction\Read(__CLASS__, $exception);
        }
    }

    /**
     * @param int $contract_id
     * @return array
     */
    public function getByContract(int $contract_id): array
    {
        try {
            return array_map([$this, 'process'], $this->promotionRepository->fetchByContract($contract_id));
        } catch (Implement\Exception\EmptyResult) {
            return [];
        }
    }

    /**
     * @param int $contract_id
     * @return array
     */
    public function getActiveByContract(int $contract_id): array
    {
        try {
            return array_map([$this, 'process'], $this->promotionRepository->fetchActiveByContract($contract_id));
        } catch (Implement\Exception\EmptyResult) {
            return [];
        }
    }

    /**
     * @param array $data
     * @return Model\Venta\Promotion
     * @throws Exception\ServiceAction\Create
     */
    public function add(array $data): Model\Venta\Promotion
    {
        try {
            $filteredData = $this->promotionRepository->filterData($data);
            $promotion = $this->promotionRepository->create($filteredData);
            return $this->process($this->promotionRepository->save($promotion));
        } catch (PDOException $exception) {
            throw new Exception\ServiceAction\Create(__CLASS__, $exception);
        }
    }

    /**
     * @param Model\Venta\Promotion $promotion
     * @param array $data
     * @return Model\Venta\Promotion
     * @throws Exception\ServiceAction\Update
     */
    public function edit(Model\Venta\Promotion $promotion, array $data): Model\Venta\Promotion
    {
        try {
            $filteredData = $this->promotionRepository->filterData($data);
            $promotion = $this->promotionRepository->edit($promotion, $filteredData);
            return $this->process($promotion);
        } catch (PDOException | Implement\Exception\EmptyResult $exception) {
            throw new Exception\ServiceAction\Update(__CLASS__, $exception);
        }
    }

    /**
     * @param int $promotion_id
     * @return Model\Venta\Promotion
     * @throws Exception\ServiceAction\Delete
     */
    public function remove(int $promotion_id): Model\Venta\Promotion
    {
        try {
            $promotion = $this->promotionRepository->fetchById($promotion_id);
            $this->promotionRepository->remove($promotion);
            return $promotion;
        } catch (PDOException | Implement\Exception\EmptyResult $exception) {
            throw new Exception\ServiceAction\Delete(__CLASS__, $exception);
        }
    }

    /**
     * @param int $promotion_id
     * @param int $project_id
     * @return Model\Venta\Promotion
     * @throws Exception\ServiceAction\Create
     */
    public function addProject(int $promotion_id, int $project_id): Model\Venta\Promotion
    {
        try {
            $promotion = $this->promotionRepository->fetchById($promotion_id);
        } catch (Implement\Exception\EmptyResult $exception) {
            throw new Exception\ServiceAction\Create(__CLASS__, $exception);
        }
        try {
            $project = $this->projectRepository->fetchById($project_id);
        } catch (Implement\Exception\EmptyResult $exception) {
            throw new Exception\ServiceAction\Create(__CLASS__, $exception);
        }
        if (in_array($project, $promotion->projects())) {
            return $this->process($promotion);
        }
        try {
            $this->promotionRepository->insertProjectForPromotion($promotion, $project->id);
            return $this->process($promotion);
        } catch (PDOException $exception) {
            throw new Exception\ServiceAction\Create(__CLASS__, $exception);
        }
    }

    /**
     * @param int $promotion_id
     * @param int $broker_rut
     * @return Model\Venta\Promotion
     * @throws Exception\ServiceAction\Create
     */
    public function addBroker(int $promotion_id, int $broker_rut): Model\Venta\Promotion
    {
        try {
            $promotion = $this->promotionRepository->fetchById($promotion_id);
        } catch (Implement\Exception\EmptyResult $exception) {
            throw new Exception\ServiceAction\Create(__CLASS__, $exception);
        }
        try {
            $broker = $this->brokerRepository->fetchById($broker_rut);
        } catch (Implement\Exception\EmptyResult $exception) {
            throw new Exception\ServiceAction\Create(__CLASS__, $exception);
        }
        if (in_array($broker, $promotion->brokers())) {
            return $this->process($promotion);
        }
        try {
            $this->promotionRepository->insertBrokerForPromotion($promotion, $broker->rut);
            return $this->process($promotion);
        } catch (PDOException $exception) {
            throw new Exception\ServiceAction\Create(__CLASS__, $exception);
        }
    }

    /**
     * @param int $promotion_id
     * @param int $project_id
     * @param int $unitType_id
     * @return Model\Venta\Promotion
     * @throws Exception\ServiceAction\Create
     */
    public function addUnitType(int $promotion_id, int $project_id, int $unitType_id): Model\Venta\Promotion
    {
        try {
            $promotion = $this->promotionRepository->fetchById($promotion_id);
        } catch (Implement\Exception\EmptyResult $exception) {
            throw new Exception\ServiceAction\Create(__CLASS__, $exception);
        }
        try {
            $project = $this->projectRepository->fetchById($project_id);
        } catch (Implement\Exception\EmptyResult $exception) {
            throw new Exception\ServiceAction\Create(__CLASS__, $exception);
        }
        try {
            $unitType = $this->tipoUnidadRepository->fetchById($unitType_id);
        } catch (Implement\Exception\EmptyResult $exception) {
            throw new Exception\ServiceAction\Create(__CLASS__, $exception);
        }
        if (in_array(['project' => $project, 'unitType' => $unitType], $promotion->unitTypes())) {
            return $this->process($promotion);
        }
        try {
            $this->promotionRepository->insertUnitTypeForPromotion($promotion, $project->id, $unitType->id);
            return $this->process($promotion);
        } catch (PDOException $exception) {
            throw new Exception\ServiceAction\Create(__CLASS__, $exception);
        }
    }

    /**
     * @param int $promotion_id
     * @param int $unit_line_id
     * @return Model\Venta\Promotion
     * @throws Exception\ServiceAction\Create
     */
    public function addUnitLine(int $promotion_id, int $unit_line_id): Model\Venta\Promotion
    {
        try {
            $promotion = $this->promotionRepository->fetchById($promotion_id);
        } catch (Implement\Exception\EmptyResult $exception) {
            throw new Exception\ServiceAction\Create(__CLASS__, $exception);
        }
        try {
            $unitLine = $this->proyectoTipoUnidadRepository->fetchById($unit_line_id);
        } catch (Implement\Exception\EmptyResult $exception) {
            throw new Exception\ServiceAction\Create(__CLASS__, $exception);
        }
        if (in_array($unitLine, $promotion->unitLines())) {
            return $this->process($promotion);
        }
        try {
            $this->promotionRepository->insertUnitLineForPromotion($promotion, $unitLine->id);
            return $this->process($promotion);
        } catch (PDOException $exception) {
            throw new Exception\ServiceAction\Create(__CLASS__, $exception);
        }
    }

    /**
     * @param int $promotion_id
     * @param int $unit_id
     * @return Model\Venta\Promotion
     * @throws Exception\ServiceAction\Create
     */
    public function addUnit(int $promotion_id, int $unit_id): Model\Venta\Promotion
    {
        try {
            $promotion = $this->promotionRepository->fetchById($promotion_id);
        } catch (Implement\Exception\EmptyResult $exception) {
            throw new Exception\ServiceAction\Create(__CLASS__, $exception);
        }
        try {
            $unit = $this->unidadRepository->fetchById($unit_id);
        } catch (Implement\Exception\EmptyResult $exception) {
            throw new Exception\ServiceAction\Create(__CLASS__, $exception);
        }
        if (in_array($unit, $promotion->units())) {
            return $this->process($promotion);
        }
        try {
            $this->promotionRepository->insertUnitForPromotion($promotion, $unit->id);
            return $this->process($promotion);
        } catch (PDOException $exception) {
            throw new Exception\ServiceAction\Create(__CLASS__, $exception);
        }
    }

    /**
     * @param int $promotion_id
     * @param int $project_id
     * @return void
     * @throws Exception\ServiceAction\Delete
     */
    public function removeProject(int $promotion_id, int $project_id): void
    {
        try {
            $promotion = $this->promotionRepository->fetchById($promotion_id);
        } catch (Implement\Exception\EmptyResult $exception) {
            throw new Exception\ServiceAction\Delete(__CLASS__, $exception);
        }
        try {
            $project = $this->projectRepository->fetchById($project_id);
        } catch (Implement\Exception\EmptyResult $exception) {
            throw new Exception\ServiceAction\Delete(__CLASS__, $exception);
        }
        try {
            $this->promotionRepository->removeProjectForPromotion($promotion, $project->id);
        } catch (PDOException $exception) {
            throw new Exception\ServiceAction\Delete(__CLASS__, $exception);
        }
    }

    /**
     * @param int $promotion_id
     * @param int $broker_rut
     * @return void
     * @throws Exception\ServiceAction\Delete
     */
    public function removeBroker(int $promotion_id, int $broker_rut): void
    {
        try {
            $promotion = $this->promotionRepository->fetchById($promotion_id);
        } catch (Implement\Exception\EmptyResult $exception) {
            throw new Exception\ServiceAction\Delete(__CLASS__, $exception);
        }
        try {
            $broker = $this->brokerRepository->fetchById($broker_rut);
        } catch (Implement\Exception\EmptyResult $exception) {
            throw new Exception\ServiceAction\Delete(__CLASS__, $exception);
        }
        try {
            $this->promotionRepository->removeBrokerForPromotion($promotion, $broker->rut);
        } catch (PDOException $exception) {
            throw new Exception\ServiceAction\Delete(__CLASS__, $exception);
        }
    }

    /**
     * @param int $promotion_id
     * @param int $project_id
     * @param int $unitType_id
     * @return void
     * @throws Exception\ServiceAction\Delete
     */
    public function removeUnitType(int $promotion_id, int $project_id, int $unitType_id): void
    {
        try {
            $promotion = $this->promotionRepository->fetchById($promotion_id);
        } catch (Implement\Exception\EmptyResult $exception) {
            throw new Exception\ServiceAction\Delete(__CLASS__, $exception);
        }
        try {
            $project = $this->projectRepository->fetchById($project_id);
        } catch (Implement\Exception\EmptyResult $exception) {
            throw new Exception\ServiceAction\Delete(__CLASS__, $exception);
        }
        try {
            $unitType = $this->tipoUnidadRepository->fetchById($unitType_id);
        } catch (Implement\Exception\EmptyResult $exception) {
            throw new Exception\ServiceAction\Delete(__CLASS__, $exception);
        }
        try {
            $this->promotionRepository->removeUnitTypeForPromotion($promotion, $project->id, $unitType->id);
        } catch (PDOException $exception) {
            throw new Exception\ServiceAction\Delete(__CLASS__, $exception);
        }
    }

    /**
     * @param int $promotion_id
     * @param int $unit_line_id
     * @return void
     * @throws Exception\ServiceAction\Delete
     */
    public function removeUnitLine(int $promotion_id, int $unit_line_id): void
    {
        try {
            $promotion = $this->promotionRepository->fetchById($promotion_id);
        } catch (Implement\Exception\EmptyResult $exception) {
            throw new Exception\ServiceAction\Delete(__CLASS__, $exception);
        }
        try {
            $unitLine = $this->proyectoTipoUnidadRepository->fetchById($unit_line_id);
        } catch (Implement\Exception\EmptyResult $exception) {
            throw new Exception\ServiceAction\Delete(__CLASS__, $exception);
        }
        try {
            $this->promotionRepository->removeUnitLineForPromotion($promotion, $unitLine->id);
        } catch (PDOException $exception) {
            throw new Exception\ServiceAction\Delete(__CLASS__, $exception);
        }
    }

    /**
     * @param int $promotion_id
     * @param int $unit_id
     * @return void
     * @throws Exception\ServiceAction\Delete
     */
    public function removeUnit(int $promotion_id, int $unit_id): void
    {
        try {
            $promotion = $this->promotionRepository->fetchById($promotion_id);
        } catch (Implement\Exception\EmptyResult $exception) {
            throw new Exception\ServiceAction\Delete(__CLASS__, $exception);
        }
        try {
            $unit = $this->unidadRepository->fetchById($unit_id);
        } catch (Implement\Exception\EmptyResult $exception) {
            throw new Exception\ServiceAction\Delete(__CLASS__, $exception);
        }
        try {
            $this->promotionRepository->removeUnitForPromotion($promotion, $unit->id);
        } catch (PDOException $exception) {
            throw new Exception\ServiceAction\Delete(__CLASS__, $exception);
        }
    }

    protected function process(Model\Venta\Promotion $model): Model\Venta\Promotion
    {
        $model->addFactory('projects', (new Implement\Repository\Factory())
            ->setCallable(function($promotion_id) {
                try {
                    return $this->projectRepository->fetchByPromotion($promotion_id);
                } catch (Implement\Exception\EmptyResult) {
                    return [];
                }
            })
            ->setArgs(['promotion_id' => $model->id]));
        $model->addFactory('brokers', (new Implement\Repository\Factory())
            ->setCallable(function($promotion_id) {
                try {
                    return $this->brokerRepository->fetchByPromotion($promotion_id);
                } catch (Implement\Exception\EmptyResult) {
                    return [];
                }
            })
            ->setArgs(['promotion_id' => $model->id]));
        $model->addFactory('unitTypes', (new Implement\Repository\Factory())
            ->setCallable(function($promotion_id) {
                try {
                    return array_map(function(array $ids) {
                        return [
                            'project' => $this->projectRepository->fetchById($ids['project_id']),
                            'unitType' => $this->tipoUnidadRepository->fetchById($ids['id'])
                        ];
                    }, $this->tipoUnidadRepository->fetchByPromotion($promotion_id));
                } catch (Implement\Exception\EmptyResult) {
                    return [];
                }
            })
            ->setArgs(['promotion_id' => $model->id])
        );
        $model->addFactory('unitLines', (new Implement\Repository\Factory())
            ->setCallable(function($promotion_id) {
                try {
                    return $this->proyectoTipoUnidadRepository->fetchByPromotion($promotion_id);
                } catch (Implement\Exception\EmptyResult) {
                    return [];
                }
            })
            ->setArgs(['promotion_id' => $model->id])
        );
        $model->addFactory('units', (new Implement\Repository\Factory())
            ->setCallable(function($promotion_id) {
                try {
                    return $this->unidadRepository->fetchByPromotion($promotion_id);
                } catch (Implement\Exception\EmptyResult) {
                    return [];
                }
            })
            ->setArgs(['promotion_id' => $model->id]));
        return $model;
    }
}
