/**
 * User API
 *
 * 用户相关接口
 * 
 */
import { httpClient } from "./http_client";
import { ApiPath } from "./api_path";
import { ApiEnvelope, unwrap } from "./response_helper";
import {
  CreditsData,
  CreditsHistoryData,
  UpdateProfileRequest,
  User,
  UserEntitlements,
  UserStatsResponse,
} from "@/data/dto/user";
import type { UserData } from "@/data/schemas/user/user";

export class UserApi {
  /**
   * 获取用户统计信息
   */
  async getUserStats(): Promise<UserStatsResponse> {
    const env = await httpClient<ApiEnvelope<unknown>>(ApiPath.userStats);
    return UserStatsResponse.fromJson(
      unwrap(env) as Record<string, unknown>
    );
  }

  /**
   * 获取个人信息
   */
  async getCurrentUser(): Promise<User> {
    const env = await httpClient<ApiEnvelope<unknown>>(ApiPath.userProfile);
    return User.fromJson(unwrap(env) as UserData);
  }

  /**
   * 更新个人资料
   */
  async updateProfile(body: UpdateProfileRequest): Promise<User> {
    const env = await httpClient<ApiEnvelope<unknown>>(ApiPath.updateProfile, {
      method: "PUT",
      body: body.toJson(),
    });
    return User.fromJson(unwrap(env) as UserData);
  }

  /**
   * 查询积分余额
   */
  async getCredits(): Promise<CreditsData> {
    const env = await httpClient<ApiEnvelope<unknown>>(ApiPath.userCredits);
    return CreditsData.fromJson(unwrap(env) as Record<string, unknown>);
  }

  /**
   * 查询积分操作历史
   */
  async getCreditsHistory(
    limit = 50,
    offset = 0
  ): Promise<CreditsHistoryData> {
    const env = await httpClient<ApiEnvelope<unknown>>(
      ApiPath.userCreditsHistory,
      { query: { limit, offset } }
    );
    return CreditsHistoryData.fromJson(
      unwrap(env) as Record<string, unknown>
    );
  }

  /**
   * 获取当前用户权益快照
   */
  async getEntitlements(): Promise<UserEntitlements> {
    const env = await httpClient<ApiEnvelope<unknown>>(ApiPath.userEntitlements);
    return UserEntitlements.fromJson(unwrap(env) as Record<string, unknown>);
  }
}

/**
 * 全局单例
 */
export const userApi = new UserApi();
