<?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;

/**
 * DeleteApiKey API Endpoint
 */
class DeleteApiKey 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', 'id'];

    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 = 'Missing required parameter: ' . $param;
                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);
        }
        $id = $params['id'] ?? '';

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

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

        // Send the refresh request with the token in the header
        $response = $this->ApiClient->delete("auth/token/{$id}", $params);

        if ($response->isSuccess()) {

            return ApiResponse::success($response->getData(), 'Api Key deleted successfully');
        }

        // Return original error response
        return ApiResponse::error(
            $response->getMessage() ?: 'Failed to delete API key',
            $response->getData(),
            $response->getStatusCode()
        );
    }
}