/**
 * Chat API
 *
 * 聊天相关接口
 * 
 */
import { httpClient } from "./http_client";
import { ApiPath } from "./api_path";
import { ApiEnvelope, unwrap } from "./response_helper";
import {
  ChatHistoryResponse,
  ChatSendResponse,
  ChatSyncData,
  ChatSyncRequest,
  ImageUploadResponse,
  SendMessageRequest,
  SttData,
  SyncMessage,
  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>
    );
  }

  /**
   * 语音转文字（multipart 上传）
   */
  async speechToText(audio: Blob | File): Promise<SttData> {
    const formData = new FormData();
    formData.append("audio", audio);
    const env = await httpClient<ApiEnvelope<unknown>>(ApiPath.chatStt, {
      method: "POST",
      body: formData,
    });
    return SttData.fromJson(unwrap(env) as Record<string, unknown>);
  }

  /**
   * 同步游客消息
   */
  async syncMessages(messages: SyncMessage[]): Promise<ChatSyncData> {
    const body = ChatSyncRequest.from({ messages });
    const env = await httpClient<ApiEnvelope<unknown>>(ApiPath.chatSync, {
      method: "POST",
      body: body.toJson(),
    });
    return ChatSyncData.fromJson(unwrap(env) as Record<string, unknown>);
  }

  /**
   * 上传图片
   */
  async uploadImage(image: Blob | File): Promise<ImageUploadResponse> {
    const formData = new FormData();
    formData.append("image", image);
    const env = await httpClient<ApiEnvelope<unknown>>(
      ApiPath.chatUploadImage,
      { method: "POST", body: formData }
    );
    return ImageUploadResponse.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();
