/**
 * API Key Validation Logic
 *
 * Core validation functions for API key management
 */

import { API_BASE_URL, API_ENDPOINTS } from './constants';
import type { ApiKeyInfo, ApiInfoResponse, ValidationResult } from './types';

/**
 * Parse API key info from API response
 * Handles various response formats (organizationSlug vs organizationId)
 */
export function parseKeyInfo(data: ApiInfoResponse): ApiKeyInfo {
  if (data.keyInfo) {
    return {
      organizationSlug: data.keyInfo.organizationSlug || data.keyInfo.organizationId || 'Unknown',
      projectSlug: data.keyInfo.projectSlug || data.keyInfo.projectId || 'Unknown',
    };
  }

  return {
    organizationSlug: 'Unknown',
    projectSlug: 'Unknown',
  };
}

/**
 * Validate API key by making request to /api/info endpoint
 *
 * @param apiKey - The API key to validate
 * @returns ValidationResult with success status, keyInfo, or error
 */
export async function validateApiKeyRequest(apiKey: string): Promise<ValidationResult> {
  if (!apiKey.trim()) {
    return {
      success: false,
      error: 'Please enter an API key',
    };
  }

  try {
    const response = await fetch(`${API_BASE_URL}${API_ENDPOINTS.INFO}`, {
      headers: {
        'X-API-Key': apiKey,
      },
    });

    if (response.ok) {
      const data: ApiInfoResponse = await response.json();
      const keyInfo = parseKeyInfo(data);

      return {
        success: true,
        keyInfo,
      };
    } else {
      // Try to parse error message from response
      try {
        const error = await response.json();
        return {
          success: false,
          error: error.message || 'Invalid API key',
        };
      } catch {
        return {
          success: false,
          error: response.status === 401 ? 'Invalid API key' : `Request failed with status ${response.status}`,
        };
      }
    }
  } catch (error) {
    console.error('API key validation error:', error);
    return {
      success: false,
      error: 'Failed to validate API key. Please check your connection.',
    };
  }
}
