'use strict';

require('../chunk-DGUM43GV.js');

// src/api/types.ts
var DEFAULT_STORAGE_KEYS = {
  AUTH_TOKEN: "auth_token",
  USER_DATA: "user_data",
  REFRESH_TOKEN: "refresh_token"
};
var DEFAULT_API_ROUTES = {
  auth: {
    login: "/auth/login",
    logout: "/auth/logout",
    register: "/auth/register",
    me: "/auth/me"
  },
  users: {
    list: "/users",
    detail: (id) => "/users/" + id,
    update: (id) => "/users/" + id,
    delete: (id) => "/users/" + id
  }
};

// src/api/BaseApiClient.ts
var BaseApiClient = class {
  constructor(config) {
    this.token = null;
    this.user = null;
    this.baseUrl = config.baseUrl;
    this.storage = config.storage;
    this.request = config.request;
    this.storageKeys = {
      ...DEFAULT_STORAGE_KEYS,
      ...config.storageKeys || {}
    };
    this.routes = {
      ...DEFAULT_API_ROUTES,
      ...config.routes || {},
      auth: {
        ...DEFAULT_API_ROUTES.auth,
        ...config.routes?.auth || {}
      },
      users: {
        ...DEFAULT_API_ROUTES.users,
        ...config.routes?.users || {}
      }
    };
  }
  /**
   * 初始化 - 从存储中加载 token 和用户信息
   */
  async init() {
    try {
      this.token = await this.storage.getItem(this.storageKeys.AUTH_TOKEN);
      const userData = await this.storage.getItem(this.storageKeys.USER_DATA);
      if (userData) {
        this.user = JSON.parse(userData);
      }
    } catch (error) {
      console.error("Failed to load auth data:", error);
    }
  }
  /**
   * 设置认证 token
   */
  async setToken(token) {
    this.token = token;
    if (token) {
      await this.storage.setItem(this.storageKeys.AUTH_TOKEN, token);
    } else {
      await this.storage.removeItem(this.storageKeys.AUTH_TOKEN);
    }
  }
  /**
   * 设置用户信息
   */
  async setUser(user) {
    this.user = user;
    if (user) {
      await this.storage.setItem(this.storageKeys.USER_DATA, JSON.stringify(user));
    } else {
      await this.storage.removeItem(this.storageKeys.USER_DATA);
    }
  }
  /**
   * 获取当前 token
   */
  getToken() {
    return this.token;
  }
  /**
   * 获取当前用户
   */
  getUser() {
    return this.user;
  }
  /**
   * 检查是否已登录
   */
  async isAuthenticated() {
    return !!this.token;
  }
  /**
   * 清除用户数据
   */
  async clearUserData() {
    await this.storage.removeItem(this.storageKeys.AUTH_TOKEN);
    await this.storage.removeItem(this.storageKeys.USER_DATA);
    if (this.storageKeys.REFRESH_TOKEN) {
      await this.storage.removeItem(this.storageKeys.REFRESH_TOKEN);
    }
    this.token = null;
    this.user = null;
  }
  /**
   * 发送请求的通用方法
   */
  async sendRequest(config) {
    try {
      const headers = {
        "Content-Type": "application/json",
        ...config.headers || {}
      };
      if (this.token) {
        headers["Authorization"] = "Bearer " + this.token;
      }
      const response = await this.request.request({
        ...config,
        url: this.baseUrl + config.url,
        headers
      });
      return response;
    } catch (error) {
      console.error("API request error:", error);
      return {
        success: false,
        error: error instanceof Error ? error.message : "\u7F51\u7EDC\u9519\u8BEF\uFF0C\u8BF7\u91CD\u8BD5"
      };
    }
  }
  /**
   * 发送 GET 请求
   */
  async get(url, params) {
    return this.sendRequest({ url, method: "GET", params });
  }
  /**
   * 发送 POST 请求
   */
  async post(url, body) {
    return this.sendRequest({ url, method: "POST", body });
  }
  /**
   * 发送 PUT 请求
   */
  async put(url, body) {
    return this.sendRequest({ url, method: "PUT", body });
  }
  /**
   * 发送 PATCH 请求
   */
  async patch(url, body) {
    return this.sendRequest({ url, method: "PATCH", body });
  }
  /**
   * 发送 DELETE 请求
   */
  async delete(url) {
    return this.sendRequest({ url, method: "DELETE" });
  }
  // ==================== 默认认证方法（子类可重写） ====================
  /**
   * 用户注册
   * 默认实现，子类可重写以添加自定义逻辑
   */
  async register(email, password, username) {
    if (!this.routes.auth?.register) {
      throw new Error("Register route is not configured");
    }
    const response = await this.post(this.routes.auth.register, {
      email,
      password,
      username
    });
    if (response.success && response.data) {
      await this.setToken(response.data.token);
      await this.setUser(response.data.user);
      await this.onAuthSuccess?.(response.data.user, response.data.token);
    } else if (!response.success) {
      await this.onAuthError?.(response.error || "Registration failed");
    }
    return response;
  }
  /**
   * 用户登录
   * 默认实现，子类可重写以添加自定义逻辑
   */
  async login(email, password) {
    if (!this.routes.auth?.login) {
      throw new Error("Login route is not configured");
    }
    const response = await this.post(this.routes.auth.login, {
      email,
      password
    });
    if (response.success && response.data) {
      await this.setToken(response.data.token);
      await this.setUser(response.data.user);
      await this.onAuthSuccess?.(response.data.user, response.data.token);
    } else if (!response.success) {
      await this.onAuthError?.(response.error || "Login failed");
    }
    return response;
  }
  /**
   * 用户退出登录
   * 默认实现，子类可重写以添加自定义逻辑
   */
  async logout() {
    if (this.routes.auth?.logout) {
      await this.post(this.routes.auth.logout);
    }
    await this.clearUserData();
    await this.onLogout?.();
  }
  /**
   * 获取当前用户信息
   * 默认实现，子类可重写以添加自定义逻辑
   */
  async getCurrentUser() {
    if (!this.routes.auth?.me) {
      throw new Error("Current user route is not configured");
    }
    const response = await this.get(this.routes.auth.me);
    if (response.success && response.data) {
      const userData = response.data.user || response.data;
      await this.setUser(userData);
      return {
        ...response,
        data: userData
      };
    }
    return response;
  }
  // ==================== 默认用户管理方法（子类可重写） ====================
  /**
   * 获取用户列表
   * 默认实现，子类可重写以添加自定义逻辑
   */
  async getUsers(params) {
    if (!this.routes.users?.list) {
      throw new Error("Users list route is not configured");
    }
    return this.get(this.routes.users.list, params);
  }
  /**
   * 获取用户详情
   * 默认实现，子类可重写以添加自定义逻辑
   */
  async getUserById(userId) {
    if (!this.routes.users?.detail) {
      throw new Error("User detail route is not configured");
    }
    return this.get(this.routes.users.detail(userId));
  }
  /**
   * 更新用户信息
   * 默认实现，子类可重写以添加自定义逻辑
   */
  async updateUser(userId, data) {
    if (!this.routes.users?.update) {
      throw new Error("User update route is not configured");
    }
    return this.put(this.routes.users.update(userId), data);
  }
  /**
   * 删除用户
   * 默认实现，子类可重写以添加自定义逻辑
   */
  async deleteUser(userId) {
    if (!this.routes.users?.delete) {
      throw new Error("User delete route is not configured");
    }
    return this.delete(this.routes.users.delete(userId));
  }
};

exports.BaseApiClient = BaseApiClient;
exports.DEFAULT_API_ROUTES = DEFAULT_API_ROUTES;
exports.DEFAULT_STORAGE_KEYS = DEFAULT_STORAGE_KEYS;
//# sourceMappingURL=index.js.map
//# sourceMappingURL=index.js.map