// frontend/src/services/authService.ts
export const authenticate = async (passphrase: string): Promise<string> => {
  // Read the API_URL from the runtime configuration and convert ws to http
  const apiUrl = window.runtimeConfig?.API_URL || 'http://localhost:8000';
  const httpApiUrl = apiUrl.replace(/^ws/, 'http');

  const response = await fetch(`${httpApiUrl}/api/auth/passphrase`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({ passphrase }),
  });

  if (!response.ok) {
    const errorData = await response.json();
    throw new Error(errorData.message || 'Authentication failed');
  }

  const data = await response.json();
  return data.sessionToken;
};

export const setSessionToken = (token: string): void => {
  localStorage.setItem('sessionToken', token);
};

export const getSessionToken = (): string | null => {
  return localStorage.getItem('sessionToken');
};

export const removeSessionToken = (): void => {
  localStorage.removeItem('sessionToken');
};
