/**
 * Chat API
 *
 * 聊天相关接口
 * 
 */
import { httpClient } from "./http_client";
import { ApiPath } from "./api_path";
import { ApiEnvelope, unwrap } from "./response_helper";
import {
  ChatHistoryResponse,
  ChatSendResponse,
  SendMessageRequest,
  UnlockHistoryResponse,
  UnlockPrivateRequest,
  UnlockPrivateResponse,
} from "@/data/dto/chat";

export class ChatApi {
  /**
   * 发送消息
   */
  async sendMessage(body: SendMessageRequest): Promise<ChatSendResponse> {
    const env = await httpClient<ApiEnvelope<unknown>>(ApiPath.chatSend, {
      method: "POST",
      body: body.toJson(),
    });
    return ChatSendResponse.fromJson(unwrap(env) as Record<string, unknown>);
  }

  /**
   * 获取聊天历史
   */
  async getHistory(limit = 50, offset = 0): Promise<ChatHistoryResponse> {
    const env = await httpClient<ApiEnvelope<unknown>>(ApiPath.chatHistory, {
      query: { limit, offset },
    });
    return ChatHistoryResponse.fromJson(
      unwrap(env) as Record<string, unknown>
    );
  }

  /**
   * 解锁单条历史付费 / 私密消息
   */
  async unlockPrivateMessage(
    body: UnlockPrivateRequest,
  ): Promise<UnlockPrivateResponse> {
    const env = await httpClient<ApiEnvelope<unknown>>(
      ApiPath.chatUnlockPrivate,
      {
        method: "POST",
        body: body.toJson(),
      },
    );
    return UnlockPrivateResponse.fromJson(
      unwrap(env) as Record<string, unknown>,
    );
  }

  /**
   * 一键解锁历史锁定消息
   */
  async unlockHistory(): Promise<UnlockHistoryResponse> {
    const env = await httpClient<ApiEnvelope<unknown>>(
      ApiPath.chatUnlockHistory,
      {
        method: "POST",
      },
    );
    return UnlockHistoryResponse.fromJson(
      unwrap(env) as Record<string, unknown>,
    );
  }
}

/**
 * 全局单例
 */
export const chatApi = new ChatApi();
