import { BaseApiClient } from '../base/BaseApiClient';
import { AuthSessionDTO } from '../../types/generated/AuthSessionDTO';
import { LoginParamsDTO } from '../../types/generated/LoginParamsDTO';
import { SignupParamsDTO } from '../../types/generated/SignupParamsDTO';
import { LoginWithIracingCallbackParamsDTO } from '../../types/generated/LoginWithIracingCallbackParamsDTO';
import { IracingAuthRedirectResultDTO } from '../../types/generated/IracingAuthRedirectResultDTO';

/**
 * Auth API Client
 *
 * Handles all authentication-related API operations.
 */
export class AuthApiClient extends BaseApiClient {
  /** Sign up with email */
  signup(params: SignupParamsDTO): Promise<AuthSessionDTO> {
    return this.post<AuthSessionDTO>('/auth/signup', params);
  }

  /** Login with email */
  login(params: LoginParamsDTO): Promise<AuthSessionDTO> {
    return this.post<AuthSessionDTO>('/auth/login', params);
  }

  /** Get current session */
  getSession(): Promise<AuthSessionDTO | null> {
    return this.request<AuthSessionDTO | null>('GET', '/auth/session', undefined, {
      allowUnauthenticated: true,
    });
  }

  /** Logout */
  logout(): Promise<void> {
    return this.post<void>('/auth/logout', {});
  }

  /** Start iRacing auth redirect */
  startIracingAuthRedirect(returnTo?: string): Promise<IracingAuthRedirectResultDTO> {
    const query = returnTo ? `?returnTo=${encodeURIComponent(returnTo)}` : '';
    return this.get<IracingAuthRedirectResultDTO>(`/auth/iracing/start${query}`);
  }

  /**
   * Convenience: build iRacing auth start URL.
   * Used by AuthService for view-layer navigation.
   */
  getIracingAuthUrl(returnTo?: string): string {
    const query = returnTo ? `?returnTo=${encodeURIComponent(returnTo)}` : '';
    return `${this.baseUrl}/auth/iracing/start${query}`;
  }

  /** Login with iRacing callback */
  loginWithIracingCallback(params: LoginWithIracingCallbackParamsDTO): 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 this.get<AuthSessionDTO>(`/auth/iracing/callback?${query.toString()}`);
  }
}
