<?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\Auth\AuthenticatedUser;
use MefisAssetBridgeCore\Api\Response\ApiResponse;
use MefisAssetBridgeCore\DTO\AuthenticatedUserDto;
use MefisAssetBridgeCore\Interfaces\EndpointInterface;

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

    /** @var AuthenticatedUser|null Authenticated user */
    private ?AuthenticatedUser $user;

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

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

    public function __construct(string $uuid, ApiClient $ApiClient, ?AuthenticatedUser $user, string $pathHash = '')
    {
        $this->ApiClient = $ApiClient;
        $this->user = $user;
        $this->uuid = $uuid;
        $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 = 'Refresh token is required';
                return false;
            }
        }

        return true;
    }

    /**
     * Send refresh token 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);
        }

        // Extract refresh token
        $refreshToken = $params['refresh_token'];

        // Set API key header with refresh token
        $headers[] = "X-API-Key: {$refreshToken}";
        unset($params['refresh_token']);
        $params['headers'] = $headers;


        $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();

        $response = $this->ApiClient->post('auth/refresh', $data, $params);

        if ($response->isSuccess()) {
            // Convert response data to AuthenticatedUserDto
            try {
                $responseData = $response->getData();
                if (is_array($responseData)) {
                    $userData = AuthenticatedUserDto::fromArray($responseData);

                    // Return the DTO in the response
                    return ApiResponse::success(['user' => $userData], 'Login successful');
                }
            } catch (\Exception $e) {
                return ApiResponse::error('Invalid response format: ' . $e->getMessage());
            }
        } else {
            if($response->getMessage() == 'Unauthorized App') {
                $keyStore = $this->ApiClient->getKeyStore();
                $keyStore->deleteKeys($this->uuid);

                $response = ApiResponse::error('Unauthorized App');
            }
        }

        return $response;
    }
}