<?php

declare(strict_types=1);

namespace External\PompoBundle\Overrides\GraphQL\Controller;

use External\PompoBundle\Overrides\GraphQL\Types\User\PompoUserInput;
use External\PompoBundle\Overrides\GraphQL\Util\PompoGraphQLUtil;
use KupShop\GraphQLBundle\ApiAdmin\Types\User\Response\UserMutateResponse;
use KupShop\GraphQLBundle\ApiAdmin\Util\CouponUtil;
use KupShop\GraphQLBundle\ApiAdmin\Util\UserUtil;
use KupShop\GraphQLBundle\Exception\GraphQLNotFoundException;
use KupShop\OrderDiscountBundle\Util\DiscountManager;
use TheCodingMachine\GraphQLite\Annotations\Mutation;
use TheCodingMachine\GraphQLite\Annotations\Query;

class PompoController
{
    public function __construct(
        private PompoGraphQLUtil $pompoGraphQLUtil,
        private UserUtil $userUtil,
        private CouponUtil $couponUtil,
        private DiscountManager $discountManager,
    ) {
    }

    /**
     * Vytvoří / zaktualizuje uživatele.
     */
    #[Mutation]
    public function pompoUserCreateOrUpdate(PompoUserInput $input): UserMutateResponse
    {
        $response = $this->userUtil->createOrUpdateUser($input);

        if ($response->result) {
            $this->pompoGraphQLUtil->updatePompoUser(
                $response->user->getId(),
                $input
            );

            $response->user = $this->userUtil->getUpdatedUser($response->user->getId());
        }

        return $response;
    }

    #[Query]
    public function pompoDiscountCode(string $code): bool
    {
        try {
            $coupon = $this->couponUtil->getCoupon($code);
        } catch (GraphQLNotFoundException) {
            $coupon = null;
        }

        if (!$coupon) {
            $this->discountManager->couponNumberExists($code, $orderDiscounts);
        }

        return true;
    }
}
