"use client";
import { UserApi, userApi } from "@/data/services/api";
import {
  CreditsData,
  CreditsHistoryData,
  UpdateProfileRequest,
  User,
  UserEntitlements,
  UserStatsResponse,
} from "@/data/dto/user";
import { Result } from "@/utils";
import type { IUserRepository } from "@/data/repositories/interfaces";
import { createLazySingleton } from "./lazy_singleton";

export class UserRepository implements IUserRepository {
  constructor(private readonly api: UserApi) {}

  /** 获取用户统计信息。 */
  async getUserStats(): Promise<Result<UserStatsResponse>> {
    return Result.wrap(() => this.api.getUserStats());
  }

  /** 获取当前登录用户信息。 */
  async getCurrentUser(): Promise<Result<User>> {
    return Result.wrap(() => this.api.getCurrentUser());
  }

  /** 更新个人资料。 */
  async updateProfile(request: UpdateProfileRequest): Promise<Result<User>> {
    return Result.wrap(() => this.api.updateProfile(request));
  }

  /** 查询积分余额。 */
  async getCredits(): Promise<Result<CreditsData>> {
    return Result.wrap(() => this.api.getCredits());
  }

  /** 查询积分操作历史，分页参数默认 limit=50, offset=0。 */
  async getCreditsHistory(
    limit = 50,
    offset = 0,
  ): Promise<Result<CreditsHistoryData>> {
    return Result.wrap(() => this.api.getCreditsHistory(limit, offset));
  }

  /** 获取当前用户权益快照。 */
  async getEntitlements(): Promise<Result<UserEntitlements>> {
    return Result.wrap(() => this.api.getEntitlements());
  }
}

/** 全局懒单例。 */
export const getUserRepository = createLazySingleton<IUserRepository>(
  () => new UserRepository(userApi),
);
