<?php

declare(strict_types=1);

namespace External\ZNZBundle\Controller;

use External\ZNZBundle\Synchronizers\OrderSynchronizer;
use External\ZNZBundle\Synchronizers\UserSynchronizer;
use External\ZNZBundle\Util\ZNZConfiguration;
use External\ZNZBundle\Util\ZNZWorker;
use KupShop\AdminBundle\AdminRequiredControllerInterface;
use KupShop\KupShopBundle\Util\ArrayUtil;
use KupShop\OrderingBundle\OrderList\OrderList;
use KupShop\SynchronizationBundle\Exception\RabbitRetryMessageException;
use Query\Operator;
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\Annotation\Route;

class ZNZController extends AbstractController implements AdminRequiredControllerInterface
{
    #[Route('/_znz/replay/')]
    public function replay(Request $request, ZNZWorker $worker): Response
    {
        $data = $request->get('data');
        if (!$data) {
            return new Response('<form method="post">
                     Data:<br>
                     <textarea cols="80" rows="20" name="data"></textarea><br>
                     <input type="submit"></form>');
        }

        $data = json_decode($request->get('data'), true);
        if (ArrayUtil::isDictionary($data)) {
            $data = [$data];
        }

        foreach ($data as $item) {
            try {
                $worker->processMessage($item);
            } catch (RabbitRetryMessageException $e) {
            }
        }

        return new Response('Replay done');
    }

    #[Route('/_znz/dump_order/{id}/')]
    public function dumpOrder(OrderSynchronizer $orderSynchronizer, OrderList $orderList, int $id): JsonResponse
    {
        $orders = $orderList->andSpec(Operator::equals(['o.id' => $id]))
            ->fetchItems()
            ->fetchDropshipmentInfo()
            ->getOrders();

        if (!($order = $orders->current())) {
            throw new NotFoundHttpException('Order not found');
        }

        return new JsonResponse(
            $orderSynchronizer->getOrderData($order)
        );
    }

    #[Route('/_znz/dump_order/{id}/payment/')]
    public function dumpOrderPayment(OrderSynchronizer $orderSynchronizer, int $id): JsonResponse
    {
        return new JsonResponse(
            $orderSynchronizer->getOrderPaymentData(
                \Order::get($id)
            )
        );
    }

    #[Route('/_znz/dump_user/{id}/')]
    public function dumpUser(UserSynchronizer $userSynchronizer, int $id): JsonResponse
    {
        return new JsonResponse(
            $userSynchronizer->getUserData(
                \User::createFromId($id)
            )
        );
    }

    #[Route('/_znz/dump_user/{id}/addresses/')]
    public function dumpUserAddresses(UserSynchronizer $userSynchronizer, int $id): JsonResponse
    {
        return new JsonResponse(
            $userSynchronizer->getUserAddresses(
                \User::createFromId($id)
            )
        );
    }

    #[Route('/_znz/helios_diffs/')]
    public function heliosDiffs(ZNZConfiguration $configuration): Response
    {
        $path = $configuration->getDocumentsUrl().'/Kontroly/rozdily.csv';

        try {
            if (($content = file_get_contents($path)) === false) {
                $content = null;
            }
        } catch (\Throwable $e) {
            $content = null;
        }

        if ($content === null) {
            throw new NotFoundHttpException('Diff file not found');
        }

        $response = new Response($content);
        $response->headers->set('Content-Encoding', 'UTF-8');
        $response->headers->set('Content-Type', 'text/csv; charset=UTF-8');
        $response->headers->set('Content-Disposition', 'attachment; filename=rozdily.csv');

        return $response;
    }
}
