import { api } from '../apiClient';
import type {
  AuthenticatedUserDTO,
  AuthSessionDTO,
  SignupParams,
  LoginParams,
  IracingAuthRedirectResult,
  LoginWithIracingCallbackParams,
} from '../../../apps/api/src/modules/auth/dto/AuthDto'; // Using generated API DTOs

export class AuthApiClient {
  async getCurrentSession(): Promise<AuthSessionDTO | null> {
    try {
      return await api.get<AuthSessionDTO>('/auth/session');
    } catch (error) {
      // Handle error, e.g., if session is not found or API is down
      console.error('Error fetching current session:', error);
      return null;
    }
  }

  async signupWithEmail(params: SignupParams): Promise<AuthSessionDTO> {
    return api.post<AuthSessionDTO>('/auth/signup', params);
  }

  async loginWithEmail(params: LoginParams): Promise<AuthSessionDTO> {
    return api.post<AuthSessionDTO>('/auth/login', params);
  }

  async startIracingAuthRedirect(returnTo?: string): Promise<IracingAuthRedirectResult> {
    const query = returnTo ? `?returnTo=${encodeURIComponent(returnTo)}` : '';
    return api.get<IracingAuthRedirectResult>(`/auth/iracing/start${query}`);
  }

  async loginWithIracingCallback(params: LoginWithIracingCallbackParams): Promise<AuthSessionDTO> {
    const query = new URLSearchParams();
    query.append('code', params.code);
    query.append('state', params.state);
    if (params.returnTo) {
      query.append('returnTo', params.returnTo);
    }
    return await api.get<AuthSessionDTO>(`/auth/iracing/callback?${query.toString()}`);
  }

  async logout(): Promise<void> {
    return api.post<void>('/auth/logout', {});
  }
}

export const authApiClient = new AuthApiClient();
