/**
 * Chat API
 *
 * 聊天相关接口
 *
 */
import {
  ChatHistoryResponse,
  ChatHistoryResponseSchema,
  ChatPreviewsResponse,
  ChatPreviewsResponseSchema,
  ChatSendResponse,
  ChatSendResponseSchema,
  ChatActionEventRequest,
  ChatActionEventRequestSchema,
  ChatActionEventResponse,
  ChatActionEventResponseSchema,
  OpeningMessageRequest,
  OpeningMessageResponse,
  OpeningMessageResponseSchema,
  SendMessageRequest,
  UnlockHistoryRequest,
  UnlockHistoryResponse,
  UnlockHistoryResponseSchema,
  UnlockPrivateRequest,
  UnlockPrivateResponse,
  UnlockPrivateResponseSchema,
} from "@/data/schemas/chat";
import { ApiPath } from "./api_path";
import { httpClient } from "./http_client";
import { ApiEnvelope, unwrap } from "./response_helper";

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

  /** 上报白名单聊天操作卡事件；eventId 用于安全重试。 */
  async recordActionEvent(
    body: ChatActionEventRequest,
  ): Promise<ChatActionEventResponse> {
    const request = ChatActionEventRequestSchema.parse(body);
    const env = await httpClient<ApiEnvelope<unknown>>(
      ApiPath.chatActionEvents,
      {
        method: "POST",
        body: request,
      },
    );
    return ChatActionEventResponseSchema.parse(unwrap(env));
  }

  /** 幂等保存当前角色的首次开场白。 */
  async saveOpeningMessage(
    body: OpeningMessageRequest,
    options?: { signal?: AbortSignal },
  ): Promise<OpeningMessageResponse> {
    const env = await httpClient<ApiEnvelope<unknown>>(
      ApiPath.chatOpeningMessage,
      {
        method: "POST",
        body,
        ...(options?.signal ? { signal: options.signal } : {}),
      },
    );
    return OpeningMessageResponseSchema.parse(unwrap(env));
  }

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

  async getPreviews(
    options?: { signal?: AbortSignal },
  ): Promise<ChatPreviewsResponse> {
    const env = await httpClient<ApiEnvelope<unknown>>(ApiPath.chatPreviews, {
      ...(options?.signal ? { signal: options.signal } : {}),
    });
    return ChatPreviewsResponseSchema.parse(unwrap(env));
  }

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

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

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