<?php

declare(strict_types=1);

namespace External\HannahBundle\Controller;

use External\HannahBundle\SAP\MappingType;
use External\HannahBundle\SAP\Synchronizer\POSOrderSynchronizer;
use External\HannahBundle\SAP\Util\DataFactory\OrderDataFactory;
use External\HannahBundle\SAP\Util\DataFactory\ReturnDataFactory;
use External\HannahBundle\SAP\Util\DataFactory\UserDataFactory;
use External\HannahBundle\SAP\Util\SAPConsumer;
use External\HannahBundle\SAP\Util\SAPUtil;
use External\HannahBundle\Util\OrderUtil;
use KupShop\AdminBundle\Util\LegacyAdminCredentials;
use KupShop\ReturnsBundle\Util\ReturnsUtil;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Routing\Attribute\Route;

class SAPController extends AbstractController
{
    #[Route('/_sap/dump_order/{orderId}/')]
    public function dumpOrder(LegacyAdminCredentials $adminCredentials, OrderDataFactory $dataFactory, OrderUtil $orderUtil, int $orderId): JsonResponse
    {
        if (!$adminCredentials->isLogged()) {
            throw new NotFoundHttpException('Not authenticated');
        }

        $order = new \Order();
        if (!$order->createFromDB($orderId)) {
            throw new NotFoundHttpException('Order not found');
        }

        return new JsonResponse(
            [
                'process' => $orderUtil->getOrderProcess($order),
                'data' => $dataFactory->getData(['order' => $order]),
            ]
        );
    }

    #[Route('/_sap/dump_user/{userId}/')]
    public function dumpUser(LegacyAdminCredentials $adminCredentials, UserDataFactory $dataFactory, int $userId): JsonResponse
    {
        if (!$adminCredentials->isLogged()) {
            throw new NotFoundHttpException('Not authenticated');
        }

        if (!($user = \User::createFromId($userId))) {
            throw new NotFoundHttpException('User not found');
        }

        return new JsonResponse(
            $dataFactory->getData(['user' => $user])
        );
    }

    #[Route('/_sap/dump_return/{returnId}/')]
    public function dumpReturn(LegacyAdminCredentials $adminCredentials, ReturnDataFactory $dataFactory, ?ReturnsUtil $returnsUtil, int $returnId): JsonResponse
    {
        if (!$adminCredentials->isLogged()) {
            throw new NotFoundHttpException('Not authenticated');
        }

        if (!$returnsUtil) {
            throw new NotFoundHttpException('Returns module is not enabled');
        }

        if (!($return = $returnsUtil->getReturn($returnId))) {
            throw new NotFoundHttpException('Return not found');
        }

        return new JsonResponse(
            $dataFactory->getData(['return' => $return])
        );
    }

    #[Route('/_sap/store_id/{sapId}/')]
    public function storeBySAPId(SAPUtil $sapUtil, string $sapId): JsonResponse
    {
        return new JsonResponse(['id' => $sapUtil->getMapping(MappingType::STORES, $sapId)]);
    }

    #[Route('/_sap/replay/')]
    public function replay(Request $request, SAPConsumer $consumer): Response
    {
        $type = $request->get('type');

        if (!$type) {
            return new Response('<form>
                     Data:<br>
                     <textarea cols="80" rows="5" name="data"></textarea><br>
                     Type:<br>
                   <select name="type">
                         <option value="catalog">Catalog</option>
                         <option value="order">Order</option>
                     </select><br>
                     <input type="submit"></form>');
        }
        $items = match ($type) {
            'catalog' => ['Items' => ['item' => [json_decode($request->get('data'), true)]]],
            'order' => json_decode($request->get('data'), true),
            default => throw new \Symfony\Component\HttpKernel\Exception\NotFoundHttpException('Invalid type'),
        };

        $consumer->handleMessageData([
            'method' => $type,
            'data_key' => 'items',
            'items' => $items,
        ]);

        return new Response(
            sprintf('Synchronization of type %s done', $type)
        );
    }

    #[Route('/_sap/pos_import/')]
    public function importPosOrders(Request $request, POSOrderSynchronizer $synchronizer): Response
    {
        if ($filename = $request->get('posFilename')) {
            $synchronizer->setPosFilename($filename);
        }

        $synchronizer->process([]);

        return new Response('Done');
    }
}
