<?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;
use Psr\Log\LoggerInterface;

/**
 * Create account controller
 *
 * Handles new SimplyIN account creation
 */
class CreateAccount implements HttpPostActionInterface, CsrfAwareActionInterface
{
    use CsrfAwareApiTrait;

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

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

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

    /**
     * @var LoggerInterface
     */
    private $logger;

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

    /**
     * Execute create account 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'] ?? '';
            $firstName = $data['firstName'] ?? '';
            $lastName = $data['lastName'] ?? '';
            $phone = $data['phone'] ?? '';

            if (empty($email) || empty($firstName) || empty($lastName) || empty($phone)) {
                return $result->setData([
                    'success' => false,
                    'message' => __('All fields are required')
                ]);
            }

            // Call Simply.IN API to create account
            $response = $this->apiClient->createAccount($email, $firstName, $lastName, $phone);

            if ($response['success']) {
                return $result->setData($this->buildSuccessResponse($response));
            } else {
                return $result->setData([
                    'success' => false,
                    'message' => $response['error'] ?? __('Failed to create account')
                ]);
            }
        } catch (\Exception $e) {
            $this->logger->error('SimplyIN CreateAccount: ' . $e->getMessage(), [
                'trace' => $e->getTraceAsString()
            ]);
            return $result->setData([
                'success' => false,
                'message' => __('An unexpected error occurred. Please try again.')
            ]);
        }
    }

    /**
     * Build the success response payload
     *
     * @param array $response
     * @return array
     */
    private function buildSuccessResponse(array $response): array
    {
        $responseData = [
            'success' => true,
            'message' => $response['message'] ?? __('Account created successfully')
        ];

        // Include auth token if available
        if (isset($response['data']['authToken'])) {
            $responseData['authToken'] = $response['data']['authToken'];
        }

        // Include if OTP is required
        if (isset($response['requiresOtp']) && $response['requiresOtp']) {
            $responseData['requiresOtp'] = true;
        }

        return $responseData;
    }
}
