<?php
/**
 * @package     MefisAssetBridge
 * @subpackage  MefisAssetBridgeCore_Api_Endpoints
 *
 * @copyright   Copyright (C) 2025 Goran Usljebrka. All rights reserved.
 * @license     Proprietary — No resale or incorporation into other projects without explicit written permission. see LICENSE.txt
 */

namespace MefisAssetBridgeCore\Api\Endpoints;

use MefisAssetBridgeCore\Api\ApiClient;
use MefisAssetBridgeCore\Api\Response\ApiResponse;
use MefisAssetBridgeCore\Auth\AuthenticatedUser;
use MefisAssetBridgeCore\Interfaces\EndpointInterface;

/**
 * Handshake API Endpoint
 */
class Handshake implements EndpointInterface
{
    /** @var ApiClient API client instance */
    private ApiClient $ApiClient;

    /** @var array Required parameters */
    private array $requiredParams = ['publicKey'];

    private string $validationError = '';
    private string $pathHash;

    public function __construct(ApiClient $ApiClient, ?AuthenticatedUser $user, string $pathHash = '')
    {
        $this->ApiClient = $ApiClient;
        $this->pathHash  = $pathHash;
    }

    /**
     * Validate request parameters
     *
     * @param array $params Request parameters
     * @return bool True if parameters are valid
     */
    public function validateParams(array $params): bool
    {

        foreach ($this->requiredParams as $param) {
            if (empty($params[$param])) {
                $this->validationError = 'Public Key Is required';
                return false;
            }
        }

        return true;
    }

    /**
     * Send login request
     *
     * @param array $params Request parameters
     * @return ApiResponse
     */
    public function sendRequest(array $params): ApiResponse
    {
        // Validate required parameters
        if (! $this->validateParams($params)) {
            return ApiResponse::error($this->validationError);
        }

        // Prepare request data - framework agnostic
        $data = [
            'public_key' => $params['publicKey'],
        ];

        $data['path'] = $this->pathHash;

        $data['device_info'] = $this->ApiClient->getDeviceInfo();
        $data['domain']      = $this->ApiClient->getDomain();
        $data['cms_user_id'] = $this->ApiClient->getCMSUserId();
        $data['cms_version'] = $this->ApiClient->getCMSVersion();
        $data['cms_type']    = $this->ApiClient->getCMSType();

        // Send the handshake request
        $response = $this->ApiClient->post('auth/handshake', $data);

        if (! $response->isSuccess()) {
            return ApiResponse::error(
                $response->getMessage() ?: 'Handshake failed',
                $response->getData(),
                $response->getStatusCode()
            );
        }

        $responseData = $response->getData();

        if (empty($responseData['public_key'])) {
            return ApiResponse::error('public Key missing in response');
        }
        if (empty($responseData['uuid'])) {
            return ApiResponse::error('UUID missing in response');
        }
        if(preg_match('/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/', $responseData['uuid']) !== 1) {
            return ApiResponse::error('UUID format is invalid');
        }
        return ApiResponse::success([
            'public_key' => base64_decode($responseData['public_key']),
            'uuid'       => $responseData['uuid'],
        ], 'Public Key received');
    }
}
