/**
 * Authentication API
 *
 * Endpoints for user authentication and session management
 */

import { get, post, setAuthTokens, clearAuthTokens } from './client';
import type {
  RegisterRequest,
  LoginRequest,
  AuthResponse,
  RefreshTokenRequest,
  UserPayload,
  SuccessResponse,
} from '@/types/api';

/**
 * Register new user
 * POST /api/v1/auth/register
 */
export async function register(data: RegisterRequest): Promise<AuthResponse> {
  const response = await post<AuthResponse>('/api/v1/auth/register', data, false);

  // Store tokens
  setAuthTokens(response.accessToken, response.refreshToken);

  return response;
}

/**
 * User login
 * POST /api/v1/auth/login
 */
export async function login(data: LoginRequest): Promise<AuthResponse> {
  const response = await post<AuthResponse>('/api/v1/auth/login', data, false);

  // Store tokens
  setAuthTokens(response.accessToken, response.refreshToken);

  return response;
}

/**
 * Refresh access token
 * POST /api/v1/auth/refresh
 */
export async function refreshToken(data: RefreshTokenRequest): Promise<{ accessToken: string }> {
  return post<{ accessToken: string }>('/api/v1/auth/refresh', data, false);
}

/**
 * Logout
 * POST /api/v1/auth/logout
 */
export async function logout(): Promise<SuccessResponse> {
  try {
    const response = await post<SuccessResponse>('/api/v1/auth/logout');
    return response;
  } finally {
    // Always clear tokens locally
    clearAuthTokens();
  }
}

/**
 * Get current user profile
 * GET /api/v1/auth/me
 */
export async function getCurrentUser(): Promise<UserPayload> {
  return get<UserPayload>('/api/v1/auth/me');
}
