/**
 * 认证API SDK包装器
 * 为所有API调用自动添加Token，不会被API生成工具覆盖
 */

import { client } from './client.gen';
import * as api from './sdk.gen';
import type { Options } from './sdk.gen';

// 获取存储的token
const getAuthToken = (): string | null => {
  try {
    const storedUser = localStorage.getItem('user');
    const user = storedUser ? JSON.parse(storedUser) : null;
    return user?.token || null;
  } catch (error) {
    console.error('获取token失败:', error);
    return null;
  }
};

// 创建带认证的客户端选项
const createAuthenticatedOptions = <TData = any, ThrowOnError extends boolean = false>(
  originalOptions: Options<TData, ThrowOnError> = {} as Options<TData, ThrowOnError>
): Options<TData, ThrowOnError> => {
  const token = getAuthToken();

  const authenticatedOptions: Options<TData, ThrowOnError> = {
    ...originalOptions,
    client: client
  };

  // 如果有token，添加到请求头
  if (token) {
    authenticatedOptions.headers = {
      ...originalOptions.headers,
      Authorization: `Bearer ${token}`
    };
    console.log('🔑 为API请求添加Token:', (originalOptions as any).url || 'unknown endpoint');
  } else {
    console.log('🚫 无Token，API请求可能未授权:', (originalOptions as any).url || 'unknown endpoint');
  }

  return authenticatedOptions;
};

// 包装所有API方法，自动添加认证
export const authenticatedSdk = {
  // 认证相关
  getCaptcha: (options?: Options) => api.getCaptchaApiV1AuthCaptchaGet(options),
  login: (options: Options) => api.loginApiV1AuthLoginPost(options),
  logout: (options?: Options) => api.logoutApiV1AuthLogoutPost(createAuthenticatedOptions(options)),
  getCurrentUser: (options?: Options) => api.getCurrentUserInfoApiV1AuthMeGet(createAuthenticatedOptions(options)),
  refreshToken: (options?: Options) => api.refreshTokenApiV1AuthRefreshPost(createAuthenticatedOptions(options)),

  // 用户管理
  getUsers: (options?: Options) => api.getUsersApiV1UsersGet(createAuthenticatedOptions(options)),
  getUser: (options: Options) => api.getUserApiV1UsersUserIdGet(createAuthenticatedOptions(options)),
  createUser: (options: Options) => api.createUserApiV1UsersPost(createAuthenticatedOptions(options)),
  updateUser: (options: Options) => api.updateUserApiV1UsersUserIdPut(createAuthenticatedOptions(options)),
  deleteUser: (options: Options) => api.deleteUserApiV1UsersUserIdDelete(createAuthenticatedOptions(options)),

  // 系统用户管理
  getSystemUsers: (options?: Options) => api.listSystemUsersApiV1UsersSystemUsersGet(createAuthenticatedOptions(options)),
  getSystemUser: (options: Options) => api.getSystemUserApiV1UsersSystemUsersUserIdGet(createAuthenticatedOptions(options)),
  createSystemUser: (options: Options) => api.createSystemUserApiV1UsersSystemUsersPost(createAuthenticatedOptions(options)),
  updateSystemUser: (options: Options) => api.updateSystemUserApiV1UsersSystemUsersUserIdPut(createAuthenticatedOptions(options)),
  deleteSystemUser: (options: Options) => api.deleteSystemUserApiV1UsersSystemUsersUserIdDelete(createAuthenticatedOptions(options)),

  // 部门管理
  getDepartments: (options?: Options) => api.getDepartmentsApiV1DepartmentsDepartmentsGet(createAuthenticatedOptions(options)),
  getDepartment: (options: Options) => api.getDepartmentApiV1DepartmentsDepartmentsDepartmentIdGet(createAuthenticatedOptions(options)),
  createDepartment: (options: Options) => api.createDepartmentApiV1DepartmentsDepartmentsPost(createAuthenticatedOptions(options)),
  updateDepartment: (options: Options) => api.updateDepartmentApiV1DepartmentsDepartmentsDepartmentIdPut(createAuthenticatedOptions(options)),
  deleteDepartment: (options: Options) => api.deleteDepartmentApiV1DepartmentsDepartmentsDepartmentIdDelete(createAuthenticatedOptions(options)),
  getDepartmentTree: (options?: Options) => api.getDepartmentTreeApiV1DepartmentsDepartmentsTreeGet(createAuthenticatedOptions(options)),

  // 租户管理
  getTenants: (options?: Options) => api.listTenantsApiV1TenantsGet(createAuthenticatedOptions(options)),
  getTenant: (options: Options) => api.getTenantApiV1TenantsTenantIdGet(createAuthenticatedOptions(options)),
  createTenant: (options: Options) => api.createTenantApiV1TenantsPost(createAuthenticatedOptions(options)),
  updateTenant: (options: Options) => api.updateTenantApiV1TenantsTenantIdPut(createAuthenticatedOptions(options)),
  deleteTenant: (options: Options) => api.deleteTenantApiV1TenantsTenantIdDelete(createAuthenticatedOptions(options)),
  getCurrentTenant: (options?: Options) => api.getCurrentTenantApiV1TenantsMeGet(createAuthenticatedOptions(options)),

  // 消息管理
  sendMessage: (options: Options) => api.sendMessageApiV1MessagesSendPost(createAuthenticatedOptions(options)),
  scheduleMessage: (options: Options) => api.scheduleMessageApiV1MessagesSchedulePost(createAuthenticatedOptions(options)),
  getMessageLogs: (options?: Options) => api.listMessageLogsApiV1MessagesLogsMessageLogsGet(createAuthenticatedOptions(options)),
  getMessageReceipts: (options: Options) => api.getMessageReceiptsApiV1MessagesLogsMessageLogsMessageIdReceiptsGet(createAuthenticatedOptions(options)),

  // 系统信息
  getSystemInfo: (options?: Options) => api.getSystemInfoApiV1SystemInfoGet(createAuthenticatedOptions(options)),
  getSystemStats: (options?: Options) => api.getSystemStatsApiV1SystemStatsGet(createAuthenticatedOptions(options)),
  getSystemMetrics: (options?: Options) => api.getSystemMetricsApiV1SystemMetricsGet(createAuthenticatedOptions(options)),
  healthCheck: (options?: Options) => api.healthCheckApiV1HealthGet(createAuthenticatedOptions(options)),

  // 日志管理
  getLoginLogs: (options?: Options) => api.getLoginLogsApiV1LogsLogsLoginGet(createAuthenticatedOptions(options)),
  getOperationLogs: (options?: Options) => api.getOperationLogsApiV1LogsLogsOperationGet(createAuthenticatedOptions(options)),
  getNetworkLogs: (options?: Options) => api.getNetworkLogsApiV1LogsLogsNetworkGet(createAuthenticatedOptions(options)),
};

// 导出原始API以供特殊情况使用（如登录）
export { api };

// 导出类型
export type { Options };