<?php

/**
 * Copyright 2024-2025 Simply.IN Sp. z o.o.
 *
 * NOTICE OF LICENSE
 *
 * Licensed under the EUPL-1.2 or later.
 * You may not use this work except in compliance with the Licence.
 *
 * Copy of the Licence is available at:
 * https://joinup.ec.europa.eu/software/page/eupl
 * It is bundled with this package in the file LICENSE.txt
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the Licence is distributed on an as is basis,
 * without warranties or conditions of any kind, either express or implied.
 * Check the Licence for the specific language governing permissions
 * and limitations under the License.
 *
 * @author   Simply.IN Sp. z o.o.
 * @copyright 2024-2025 Simply.IN Sp. z o.o.
 * @license   https://joinup.ec.europa.eu/software/page/eupl
 */

declare(strict_types=1);

namespace SimplyIn\Ajax\Handler;

use Context;
use PrestaShopLogger;
use SimplyIn\Ajax\AjaxActionInterface;
use SimplyIn\Ajax\AjaxRequest;
use SimplyIn\Ajax\Service\CustomerService;
use SimplyIn\Ajax\Service\DeliveryFormRenderer;
use SimplyIn\Api\SimplyInApiClient;
use SimplyIn\Session\SimplyInSessionInterface;
use Throwable;

if (!defined('_PS_VERSION_')) {
    exit;
}

final class CheckCodeHandler implements AjaxActionInterface
{
    public function __construct(
        private readonly SimplyInApiClient $api,
        private readonly Context $context,
        private readonly SimplyInSessionInterface $session,
        private readonly CustomerService $customerService,
        private readonly DeliveryFormRenderer $renderer,
    ) {
    }

    public function name(): string
    {
        return 'checkCode';
    }

    public function execute(AjaxRequest $request): array
    {
        $email = $request->getString('email');
        if ($request->getBool('force_login') && $this->context->customer !== null) {
            $email = (string) $this->context->customer->email;
        }

        $raw = $this->api->apiCall([
            'email' => $email,
            'code' => $request->getString('code'),
            'notificationTokenId' => $request->getString('notificationTokenId'),
        ], 'POST', 'checkout/submitCheckoutCodeCommerce');
        $response = is_array($raw) ? $raw : [];

        if (empty($response['isCodeValid'])) {
            return $response;
        }

        // Only persist tokens the backend actually returned — writing '' when a key is absent would
        // clobber a still-valid session and break subsequent authenticated calls. Strip them from the
        // returned payload so they never reach the browser.
        if (isset($response['authToken'])) {
            $this->session->set('simplyin_auth_token', (string) $response['authToken']);
        }
        if (isset($response['refreshToken'])) {
            $this->session->set('simplyin_refresh_token', (string) $response['refreshToken']);
        }
        unset($response['authToken'], $response['refreshToken']);

        // The one-time OTP code has ALREADY been consumed by the backend at this point (isCodeValid).
        // Any failure in the post-validation side effects (customer login/create, delivery-form
        // render) must NOT bubble out as a generic controller error that hides an already-valid code
        // and leaves the widget silent. Surface it as an explicit, retryable in-widget error instead,
        // keeping isCodeValid:true so the front never re-shows "invalid code" for a code that was fine.
        try {
            $response['login_result'] = $this->customerService->loginOrCreateByEmail($email, $response);
            $response['html'] = $this->renderer->render($response);
            $response['success'] = true;
        } catch (Throwable $e) {
            PrestaShopLogger::addLog(
                'SimplyIn checkCode post-validation failure: ' . $e->getMessage()
                . ' @ ' . $e->getFile() . ':' . $e->getLine() . "\n" . $e->getTraceAsString(),
                3,
            );
            $response['success'] = false;
            $response['error'] = 'POST_VALIDATION_FAILURE';
        }

        return $response;
    }
}
