// @/api/auth.ts
import apiClient from './index';
import type { 
  LoginRequest, 
  LoginResponse, 
  SignUpRequest,
  ResetPasswordWithCodeRequest
} from './types';

/**
 * 用户登录（使用 Fetch API）
 * @param credentials - 登录凭据 (邮箱和密码)
 * @returns Promise<LoginResponse>
 */
export const loginWithFetch = async (credentials: LoginRequest): Promise<LoginResponse> => {
  const response = await fetch('/api/auth/login', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(credentials),
  });

  if (!response.ok) {
    let errorMessage = `HTTP error ${response.status}: ${response.statusText}`;
    const responseText = await response.text();
    try {
      const errorBody = JSON.parse(responseText);
      if (errorBody && errorBody.message) {
        errorMessage = errorBody.message;
      } else if (responseText) {
        errorMessage = responseText;
      }
    } catch (e) {
      if (responseText) {
        errorMessage = responseText;
      }
    }
    const error: any = new Error(errorMessage);
    error.status = response.status;
    throw error;
  }

  // If response is OK, we need to parse it as JSON.
  // The stream hasn't been read if response.ok is true.
  const data = await response.json();
  return data;
};

/**
 * 用户登录
 * @param credentials - 登录凭据 (邮箱和密码)
 * @returns Promise<AxiosResponse<LoginResponse>>
 */
export const login = (credentials: LoginRequest) => {
  return apiClient.post<LoginResponse>('/auth/login', credentials);
};

/**
 * 用户注册
 * @param data - 注册所需信息
 */
export const signup = (data: SignUpRequest) => {
  return apiClient.post('/auth/signup', data);
};

/**
 * 发送【注册】验证码
 * @param email - 目标邮箱
 */
export const sendVerificationCode = (email: string) => {
  return apiClient.post(`/auth/send-verification-code?email=${email}`);
};

/**
 * 发送【密码重置】验证码
 * @param email - 目标邮箱
 */
export const sendPasswordResetCode = (email: string) => {
  return apiClient.post(`/auth/send-password-reset-code?email=${email}`);
};

/**
 * 使用验证码重置密码
 * @param data - 包含邮箱、验证码和新密码的对象
 */
export const resetPasswordWithCode = (data: ResetPasswordWithCodeRequest) => {
  return apiClient.post('/auth/reset-password-with-code', data);
};

/**
 * 用户登出
 * 通知后端记录登出操作
 */
export const logout = () => {
  return apiClient.post('/auth/logout');
};

// ... 其他认证相关的API调用 