/**
 * 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 & { rememberMe?: boolean }): Promise<AuthResponse> {
  const { rememberMe, ...loginData } = data;
  const response = await post<AuthResponse>('/api/v1/auth/login', loginData, false);

  // Store tokens — localStorage if rememberMe, sessionStorage otherwise
  setAuthTokens(response.accessToken, response.refreshToken, rememberMe ?? false);

  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');
}

/**
 * Contact form — send message to contact@xpeditis.com
 * POST /api/v1/auth/contact
 */
export async function sendContactForm(data: {
  firstName: string;
  lastName: string;
  email: string;
  company?: string;
  phone?: string;
  subject: string;
  message: string;
}): Promise<{ message: string }> {
  return post<{ message: string }>('/api/v1/auth/contact', data, false);
}

/**
 * Forgot password — request reset email
 * POST /api/v1/auth/forgot-password
 */
export async function forgotPassword(email: string): Promise<{ message: string }> {
  return post<{ message: string }>('/api/v1/auth/forgot-password', { email }, false);
}

/**
 * Reset password with token from email
 * POST /api/v1/auth/reset-password
 */
export async function resetPassword(
  token: string,
  newPassword: string
): Promise<{ message: string }> {
  return post<{ message: string }>('/api/v1/auth/reset-password', { token, newPassword }, false);
}
