import { request } from '@umijs/max';
import { saveTokens, saveUserInfo, clearTokens, getRefreshToken, updateAccessToken } from './tokenManager';

const AUTH_BASE_URL = process.env.Auth_URL || '';

// 预注册（发送验证码）
export async function preRegister(params: AuthAPI.PreRegisterParams): Promise<AuthAPI.Response<AuthAPI.PreRegisterData>> {
  return request(`${AUTH_BASE_URL}/api/auth/pre-register`, {
    method: 'POST',
    data: params,
    skipErrorHandler: true,
  });
}

// 重发注册验证码
export async function resendRegisterCode(params: AuthAPI.ResendCodeParams): Promise<AuthAPI.Response<AuthAPI.PreRegisterData>> {
  return request(`${AUTH_BASE_URL}/api/auth/pre-register/resend`, {
    method: 'POST',
    data: params,
    skipErrorHandler: true,
  });
}

// 验证注册（创建用户）
export async function verifyRegister(params: AuthAPI.VerifyRegisterParams): Promise<AuthAPI.Response<AuthAPI.VerifyRegisterData>> {
  const response = await request<AuthAPI.Response<AuthAPI.VerifyRegisterData>>(`${AUTH_BASE_URL}/api/auth/register/verify`, {
    method: 'POST',
    data: params,
    skipErrorHandler: true,
  });

  // 注册成功后保存 Token 和用户信息
  if (response.success && response.data) {
    saveTokens(response.data.tokens);
    saveUserInfo(response.data.user);
  }

  return response;
}

// 预登录（验证密码+发送验证码）
export async function preLogin(params: AuthAPI.PreLoginParams): Promise<AuthAPI.Response<AuthAPI.PreLoginData>> {
  return request(`${AUTH_BASE_URL}/api/auth/pre-login`, {
    method: 'POST',
    data: params,
    skipErrorHandler: true,
  });
}

// 重发登录验证码
export async function resendLoginCode(params: AuthAPI.ResendCodeParams): Promise<AuthAPI.Response<AuthAPI.PreLoginData>> {
  return request(`${AUTH_BASE_URL}/api/auth/pre-login/resend`, {
    method: 'POST',
    data: params,
    skipErrorHandler: true,
  });
}

// 验证登录（返回Token）
export async function verifyLogin(params: AuthAPI.VerifyLoginParams): Promise<AuthAPI.Response<AuthAPI.VerifyLoginData>> {
  const response = await request<AuthAPI.Response<AuthAPI.VerifyLoginData>>(`${AUTH_BASE_URL}/api/auth/login/verify`, {
    method: 'POST',
    data: params,
    skipErrorHandler: true,
  });

  // 登录成功后保存 Token 和用户信息
  if (response.success && response.data) {
    saveTokens(response.data.tokens);
    saveUserInfo(response.data.user);
  }

  return response;
}

// Google 登录
export async function googleLogin(params: AuthAPI.GoogleLoginParams): Promise<AuthAPI.Response<AuthAPI.GoogleLoginData>> {
  // 使用原生 fetch 避免请求拦截器的 token 刷新逻辑
  const response = await fetch(`${AUTH_BASE_URL}/api/auth/google-login`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(params),
  });

  const data = await response.json() as AuthAPI.Response<AuthAPI.GoogleLoginData>;

  // 登录成功后保存 Token 和用户信息
  if (data.success && data.data) {
    saveTokens(data.data.tokens);
    saveUserInfo(data.data.user);
  }

  return data;
}

// 忘记密码（发送验证码）
export async function forgotPassword(params: AuthAPI.ForgotPasswordParams): Promise<AuthAPI.Response<{ email: string; expiresIn: number }>> {
  return request(`${AUTH_BASE_URL}/api/auth/forgot-password`, {
    method: 'POST',
    data: params,
    skipErrorHandler: true,
  });
}

// 重发忘记密码验证码
export async function resendForgotPasswordCode(params: AuthAPI.ResendCodeParams): Promise<AuthAPI.Response<{ email: string; expiresIn: number }>> {
  return request(`${AUTH_BASE_URL}/api/auth/forgot-password/resend`, {
    method: 'POST',
    data: params,
    skipErrorHandler: true,
  });
}

// 重置密码
export async function resetPassword(params: AuthAPI.ResetPasswordParams): Promise<AuthAPI.Response<{ message: string }>> {
  return request(`${AUTH_BASE_URL}/api/auth/reset-password`, {
    method: 'POST',
    data: params,
    skipErrorHandler: true,
  });
}

// 用户登出
export async function logout(): Promise<AuthAPI.Response<void>> {
  const response = await request<AuthAPI.Response<void>>(`${AUTH_BASE_URL}/api/auth/logout`, {
    method: 'POST',
    skipErrorHandler: true,
  });

  // 无论成功与否，都清除本地 Token
  clearTokens();

  return response;
}

// 刷新 Token
export async function refreshToken(): Promise<AuthAPI.Response<AuthAPI.RefreshTokenData>> {
  const refreshTokenValue = getRefreshToken();

  if (!refreshTokenValue) {
    return {
      success: false,
      message: 'No refresh token available',
      error: { code: 'E093' },
    };
  }

  const response = await request<AuthAPI.Response<AuthAPI.RefreshTokenData>>(`${AUTH_BASE_URL}/api/auth/refresh-token`, {
    method: 'POST',
    data: { refreshToken: refreshTokenValue },
    skipErrorHandler: true,
  });

  // 刷新成功后更新 Access Token
  if (response.success && response.data) {
    updateAccessToken(response.data.accessToken, response.data.accessTokenExpiry);
  }

  return response;
}

// 获取当前用户信息
export async function getCurrentUser(): Promise<AuthAPI.Response<AuthAPI.ProfileData>> {
  return request(`${AUTH_BASE_URL}/api/auth/profile`, {
    method: 'GET',
    skipErrorHandler: true,
  });
}

// 修改用户信息
export async function updateProfile(params: AuthAPI.UpdateProfileParams): Promise<AuthAPI.Response<{ user: AuthAPI.UserInfo }>> {
  const response = await request<AuthAPI.Response<{ user: AuthAPI.UserInfo }>>(`${AUTH_BASE_URL}/api/auth/profile`, {
    method: 'PUT',
    data: params,
    skipErrorHandler: true,
  });

  // 更新成功后保存用户信息
  if (response.success && response.data) {
    saveUserInfo(response.data.user);
  }

  return response;
}

// 修改密码
export async function changePassword(params: AuthAPI.ChangePasswordParams): Promise<AuthAPI.Response<AuthAPI.ChangePasswordData>> {
  return request(`${AUTH_BASE_URL}/api/auth/change-password`, {
    method: 'POST',
    data: params,
    skipErrorHandler: true,
  });
}

// 获取邮箱状态
export async function getEmailStatus(): Promise<AuthAPI.Response<AuthAPI.EmailStatusData>> {
  return request(`${AUTH_BASE_URL}/api/email/status`, {
    method: 'GET',
    skipErrorHandler: true,
  });
}

// 发送当前邮箱验证码
export async function sendCurrentEmailCode(params: AuthAPI.SendEmailCodeParams): Promise<AuthAPI.Response<AuthAPI.SendEmailCodeData>> {
  return request(`${AUTH_BASE_URL}/api/email/send-verification-code`, {
    method: 'POST',
    data: params,
    skipErrorHandler: true,
  });
}

// 发送新邮箱验证码
export async function sendNewEmailCode(params: AuthAPI.SendEmailCodeParams): Promise<AuthAPI.Response<AuthAPI.SendEmailCodeData>> {
  return request(`${AUTH_BASE_URL}/api/email/send-new-email-code`, {
    method: 'POST',
    data: params,
    skipErrorHandler: true,
  });
}

// 验证当前邮箱
export async function verifyCurrentEmail(params: AuthAPI.VerifyCurrentEmailParams): Promise<AuthAPI.Response<AuthAPI.VerifyCurrentEmailData>> {
  return request(`${AUTH_BASE_URL}/api/email/change`, {
    method: 'POST',
    data: params,
    skipErrorHandler: true,
  });
}

// 绑定新邮箱
export async function bindNewEmail(params: AuthAPI.BindNewEmailParams): Promise<AuthAPI.Response<AuthAPI.BindNewEmailData>> {
  const response = await request<AuthAPI.Response<AuthAPI.BindNewEmailData>>(`${AUTH_BASE_URL}/api/email/change`, {
    method: 'POST',
    data: params,
    skipErrorHandler: true,
  });

  // 更新成功后保存用户信息
  if (response.success && response.data) {
    saveUserInfo(response.data.user);
  }

  return response;
}

// 上传文件
const BUCKETS_URL = process.env.Buckets_URL || '';

export async function uploadFile(file: File): Promise<{ code: number; message: string; data: AuthAPI.UploadFileData }> {
  const formData = new FormData();
  formData.append('file', file);

  return request(`${BUCKETS_URL}/api/proxy/upload`, {
    method: 'POST',
    data: formData,
    skipErrorHandler: true,
  });
}

// ============ 个人 API Key 管理 ============

// 获取我的 API Key 列表
export async function getMyApiKeys(): Promise<AuthAPI.Response<AuthAPI.ApiKeyListData>> {
  return request(`${AUTH_BASE_URL}/api/keys`, {
    method: 'GET',
    skipErrorHandler: true,
  });
}

// 创建 API Key
export async function createApiKey(params: AuthAPI.CreateApiKeyParams): Promise<AuthAPI.Response<AuthAPI.CreateApiKeyData>> {
  return request(`${AUTH_BASE_URL}/api/keys`, {
    method: 'POST',
    data: params,
    skipErrorHandler: true,
  });
}

// 撤销 API Key
export async function revokeApiKey(id: string): Promise<AuthAPI.Response<void>> {
  return request(`${AUTH_BASE_URL}/api/keys/${id}`, {
    method: 'DELETE',
    skipErrorHandler: true,
  });
}

// ============ 会话管理 ============

// 获取会话/设备列表
export async function getSessions(params?: AuthAPI.GetSessionsParams): Promise<AuthAPI.Response<AuthAPI.SessionListData>> {
  return request(`${AUTH_BASE_URL}/api/sessions`, {
    method: 'GET',
    params,
    skipErrorHandler: true,
  });
}

// 获取活跃会话数
export async function getSessionCount(): Promise<AuthAPI.Response<AuthAPI.SessionCountData>> {
  return request(`${AUTH_BASE_URL}/api/sessions/count`, {
    method: 'GET',
    skipErrorHandler: true,
  });
}

// 获取登录历史记录
export async function getLoginHistory(params?: AuthAPI.GetLoginHistoryParams): Promise<AuthAPI.Response<AuthAPI.LoginHistoryData>> {
  return request(`${AUTH_BASE_URL}/api/sessions/history`, {
    method: 'GET',
    params,
    skipErrorHandler: true,
  });
}

// 撤销指定会话（远程下线设备）
export async function revokeSession(id: string): Promise<AuthAPI.Response<void>> {
  return request(`${AUTH_BASE_URL}/api/sessions/${id}`, {
    method: 'DELETE',
    skipErrorHandler: true,
  });
}

// 下线所有其他设备
export async function revokeOtherSessions(): Promise<AuthAPI.Response<AuthAPI.RevokeOthersData>> {
  return request(`${AUTH_BASE_URL}/api/sessions/revoke-others`, {
    method: 'POST',
    skipErrorHandler: true,
  });
}

// ============ 操作日志 ============

// 获取操作日志
export async function getAuthOperationLogs(
  params?: AuthAPI.GetAuthOperationLogsParams,
): Promise<AuthAPI.GetAuthOperationLogsResponse> {
  return request(`${AUTH_BASE_URL}/api/admin/operation-logs`, {
    method: 'GET',
    params,
  });
}

// 获取每日活跃统计（DAU）
export async function getDailyStats(
  params?: AuthAPI.GetDailyStatsParams,
): Promise<AuthAPI.GetDailyStatsResponse> {
  return request(`${AUTH_BASE_URL}/api/admin/operation-logs/daily-stats`, {
    method: 'GET',
    params,
  });
}

// 获取每日返佣统计
export async function getDailyCommissionStats(
  params?: AuthAPI.GetDailyCommissionStatsParams,
): Promise<AuthAPI.GetDailyCommissionStatsResponse> {
  return request(`${AUTH_BASE_URL}/api/admin/operation-logs/daily-commission-stats`, {
    method: 'GET',
    params,
  });
}

// 手动重算统计数据
export async function recalculateStats(
  params: AuthAPI.RecalculateStatsParams,
): Promise<AuthAPI.RecalculateStatsResponse> {
  return request(`${AUTH_BASE_URL}/api/admin/operation-logs/recalculate-stats`, {
    method: 'POST',
    data: params,
  });
}
