<?php
namespace Incoviba\Controller\API\Proyectos\Brokers;

use DateTimeImmutable;
use DateMalformedStringException;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Incoviba\Common\Implement;
use Incoviba\Controller\API\withJson;
use Incoviba\Exception\ServiceAction;
use Incoviba\Repository;
use Incoviba\Service;
use Psr\Log\LoggerInterface;

class Contracts
{
    use withJson;

    public function __invoke(ServerRequestInterface $request, ResponseInterface $response,
                             Service\Proyecto\Broker\Contract $contractService): ResponseInterface
    {
        $contracts = $contractService->getAll();

        return $this->withJson($response, compact('contracts'));
    }
    public function getByBroker(ServerRequestInterface $request, ResponseInterface $response,
                                Service\Proyecto\Broker\Contract $contractService,
                                Service\Proyecto\Broker $brokerService, int $broker_rut): ResponseInterface
    {
        $output = [
            'broker_rut' => $broker_rut,
            'contracts' => []
        ];
        try {
            $broker = $brokerService->get($broker_rut);
            $output['contracts'] = $contractService->getByBroker($broker->rut);
        } catch (ServiceAction\Read $exception) {
            return $this->withError($response, $exception);
        }
        return $this->withJson($response, $output);
    }
    public function get(ServerRequestInterface $request, ResponseInterface $response,
                        Service\Proyecto\Broker\Contract $contractService, int $contract_id): ResponseInterface
    {
        $output = [
            'contract_id' => $contract_id,
            'contract' => null
        ];
        try {
            $output['contract'] = $contractService->getById($contract_id);
        } catch (ServiceAction\Read $exception) {
            return $this->withError($response, $exception);
        }

        return $this->withJson($response, $output);
    }
    public function add(ServerRequestInterface $request, ResponseInterface $response,
                        Service\Proyecto\Broker\Contract $contractService): ResponseInterface
    {
        $input = $request->getParsedBody();
        $output = [
            'input' => $input,
            'contracts' => [],
            'success' => false,
            'partial' => false,
            'errors' => [],
        ];
        foreach ($input['contracts'] as $jsonData) {
            try {
                $contractData = json_decode($jsonData, true);
                if (is_array($jsonData)) {
                    $contractData = $jsonData;
                }
                $contract = $contractService->add($contractData);
                $output['contracts'] []= [
                    'contract' => $contract,
                    'success' => true
                ];
                $output['partial'] = true;
            } catch (ServiceAction\Create $exception) {
                $output['errors'] []= $this->parseError($exception);
            }
        }
        if (count($output['contracts']) == count($input['contracts'])) {
            $output['success'] = true;
        }

        return $this->withJson($response, $output);
    }
    public function edit(ServerRequestInterface $request, ResponseInterface $response,
                         Service\Proyecto\Broker\Contract $contractService, int $contract_id): ResponseInterface
    {
        $input = $request->getParsedBody();
        $output = [
            'contract_id' => $contract_id,
            'input' => $input,
            'contract' => null,
            'success' => false
        ];
        try {
            $contract = $contractService->getById($contract_id);
            $output['contract'] = $contractService->edit($contract, $input);
            $output['success'] = true;
        } catch (ServiceAction\Read | ServiceAction\Update $exception) {
            return $this->withError($response, $exception);
        }

        return $this->withJson($response, $output);
    }
    public function inactive(ServerRequestInterface $request, ResponseInterface $response,
                             Service\Proyecto\Broker\Contract $contractService, int $contract_id): ResponseInterface
    {
        $input = $request->getParsedBody();
        $output = [
            'contract_id' => $contract_id,
            'input' => $input,
            'contract' => null,
            'success' => false
        ];
        try {
            $contract = $contractService->getById($contract_id);
            $date = new DateTimeImmutable();
            if (!empty($input['date'])) {
                try {
                    $date = new DateTimeImmutable($input['date']);
                } catch (DateMalformedStringException) {}
            }
            $output['contract'] = $contractService->inactive($contract, $date);
            $output['success'] = true;
        } catch (ServiceAction\Read | ServiceAction\Update $exception) {
            return $this->withError($response, $exception);
        }

        return $this->withJson($response, $output);
    }
    public function delete(ServerRequestInterface $request, ResponseInterface $response,
                           Service\Proyecto\Broker\Contract $contractService, int $contract_id): ResponseInterface
    {
        $output = [
            'contract_id' => $contract_id,
            'contract' => null,
            'success' => false
        ];
        try {
            $output['contract'] = $contractService->delete($contract_id);
            $output['success'] = true;
        } catch (ServiceAction\Delete $exception) {
            return $this->withError($response, $exception);
        }

        return $this->withJson($response, $output);
    }

    public function promotions(ServerRequestInterface $request, ResponseInterface $response,
                               Service\Proyecto\Broker\Contract $contractService,
                               Repository\Venta\Unidad $unitRepository,
                               Repository\Venta\Promotion $promotionRepository,
                               LoggerInterface $logger,
                               int $contract_id): ResponseInterface
    {
        $input = $request->getParsedBody();
        $output = [
            'contract_id' => $contract_id,
            'input' => $input,
            'unidades' => [],
        ];
        $unit_ids = $input['unidad_ids'];
        if (is_string($unit_ids)) {
            $unit_ids = json_decode($input['unidad_ids'], true);
        }
        try {
            $output['unidades'] = $promotionRepository->fetchByContractAndUnits($contract_id, $unit_ids);
        } catch (Implement\Exception\EmptyResult $exception) {
            $logger->debug($exception);
        }
        return $this->withJson($response, $output);
    }
}
