<?php

namespace KupShop\IncomakerBundle\Controller;

use KupShop\IncomakerBundle\Util\XMLResponse;
use KupShop\UserBundle\Util\UserConsent;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;

class IncomakerController extends AbstractController
{
    #[Route('/_incomaker/feed/')]
    public function incomakerFeedAction(Request $request, XMLResponse $XMLResponse): Response
    {
        increaseMemoryLimit(200);
        $key = $request->query->get('key');
        $type = $request->query->get('type');

        if (empty($key) || empty($type)) {
            return new Response('Empty mandatory parameters (key, type)', 400);
        }

        if (!in_array($type, array_keys(XMLResponse::getSubscribedServices()))) {
            return new Response('Wrong type', 400);
        }

        $api_key = \Settings::getDefault()['incomaker']['api_key'] ?? null;
        if ($key != $api_key) {
            return new Response('Wrong api key', 400);
        }

        return $XMLResponse->getResponse($request, $type);
    }

    #[Route('/_incomaker/unsubscribe/')]
    public function unsubscribeAction(Request $request, UserConsent $userConsent): Response
    {
        return $this->updateNewsletter($request, $userConsent, 'N');
    }

    #[Route('/_incomaker/subscribe/')]
    public function subscribeAction(Request $request, UserConsent $userConsent): Response
    {
        return $this->updateNewsletter($request, $userConsent, 'Y');
    }

    protected function updateNewsletter(Request $request, UserConsent $userConsent, $newsletter): Response
    {
        $key = $request->query->get('api');
        $contactId = $request->query->get('contactId');
        if (empty($key) || empty($contactId)) {
            return new Response('Empty mandatory parameter', 400);
        }

        $api_key = \Settings::getDefault()['incomaker']['api_key'] ?? null;
        if ($key != $api_key) {
            return new Response('Wrong api key', 400);
        }

        $user = \User::createFromId($contactId);
        if (!$user) {
            return new Response("User doesn't exist", 400);
        }

        $result = $userConsent->updateNewsletter($user->id, $newsletter, false, true);

        return new Response((string) $result, 200);
    }
}
