<?php
/**
 * Copyright © Simplyin. All rights reserved.
 */
declare(strict_types=1);

namespace Simplyin\Payment\Controller\Api;

use Magento\Framework\App\Action\HttpPostActionInterface;
use Magento\Framework\App\CsrfAwareActionInterface;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\Controller\Result\JsonFactory;
use Simplyin\Payment\Helper\ApiClient;

/**
 * Verify OTP controller
 *
 * Verifies OTP code for user authentication
 */
class VerifyOtp implements HttpPostActionInterface, CsrfAwareActionInterface
{
    use CsrfAwareApiTrait;

    /**
     * @var JsonFactory
     */
    private JsonFactory $resultJsonFactory;

    /**
     * @var ApiClient
     */
    private ApiClient $apiClient;

    /**
     * @var RequestInterface
     */
    private RequestInterface $request;

    /**
     * @param JsonFactory $resultJsonFactory
     * @param ApiClient $apiClient
     * @param RequestInterface $request
     */
    public function __construct(
        JsonFactory $resultJsonFactory,
        ApiClient $apiClient,
        RequestInterface $request
    ) {
        $this->resultJsonFactory = $resultJsonFactory;
        $this->apiClient = $apiClient;
        $this->request = $request;
    }

    /**
     * Execute verify OTP action
     *
     * @return \Magento\Framework\Controller\Result\Json
     */
    public function execute()
    {
        $result = $this->resultJsonFactory->create();

        try {
            $data = json_decode($this->request->getContent(), true);
            $email = $data['email'] ?? '';
            $code = $data['code'] ?? '';

            if (empty($email) || empty($code)) {
                return $result->setData([
                    'success' => false,
                    'message' => __('Email and OTP code are required')
                ]);
            }

            $response = $this->apiClient->verifyOtp($email, $code);

            if ($response['success'] && isset($response['data']['authToken'])) {
                $authToken = $response['data']['authToken'];
                $userData = $response['data']['data'] ?? [];

                $userDataResponse = $this->apiClient->getUserData($authToken);
                if ($userDataResponse['success']) {
                    $userData = $userDataResponse['data'];
                    if (isset($userData['data'])) {
                        $userData = $userData['data'];
                    }
                }

                return $result->setData([
                    'success' => true,
                    'authToken' => $authToken,
                    'userData' => $userData,
                    'message' => __('OTP verified successfully')
                ]);
            }

            return $result->setData([
                'success' => false,
                'message' => $response['error'] ?? __('Invalid OTP')
            ]);
        } catch (\Exception $e) {
            return $result->setData([
                'success' => false,
                'message' => __('An unexpected error occurred. Please try again.')
            ]);
        }
    }
}
