"use client";

import type {
  ChatHistoryResponse,
  ChatMessage,
  ChatSendResponse,
  UnlockHistoryResponse,
  UnlockPrivateResponse,
} from "@/data/dto/chat";
import type { ChatLockDetailData } from "@/data/schemas/chat";
import { chatApi } from "@/data/services/api";
import {
  LocalChatMediaStorage,
  LocalChatStorage,
  type LocalChatMediaRow,
} from "@/data/storage/chat";
import type {
  CacheRemoteChatMediaInput,
  ChatMediaLookupInput,
  IChatRepository,
} from "@/data/repositories/interfaces";
import type { Result } from "@/utils";

import { ChatLocalMessageStore } from "./chat_local_message_store";
import { ChatMediaCacheCoordinator } from "./chat_media_cache_coordinator";
import { ChatRemoteDataSource } from "./chat_remote_data_source";
import { createLazySingleton } from "./lazy_singleton";

export class ChatRepository implements IChatRepository {
  constructor(
    private readonly remote: ChatRemoteDataSource,
    private readonly localMessages: ChatLocalMessageStore,
    private readonly mediaCache: ChatMediaCacheCoordinator,
  ) {}

  // ============ 远程操作 ============

  /** 发送一条消息。 */
  async sendMessage(
    message: string,
    options?: { image?: string; useWebSocket?: boolean },
  ): Promise<Result<ChatSendResponse>> {
    return this.remote.sendMessage(message, options);
  }

  /** 获取聊天历史，分页参数默认 limit=50, offset=0。 */
  async getHistory(
    limit = 50,
    offset = 0,
  ): Promise<Result<ChatHistoryResponse>> {
    return this.remote.getHistory(limit, offset);
  }

  /** 解锁单条历史付费 / 私密消息。 */
  async unlockPrivateMessage(
    messageId: string,
  ): Promise<Result<UnlockPrivateResponse>> {
    return this.remote.unlockPrivateMessage(messageId);
  }

  /** 一键解锁历史锁定消息。 */
  async unlockHistory(): Promise<Result<UnlockHistoryResponse>> {
    return this.remote.unlockHistory();
  }

  /** 把本地缓存中的单条锁定消息标记为已解锁。 */
  async markPrivateMessageUnlockedInLocal(
    messageId: string,
    lockDetail?: ChatLockDetailData,
  ): Promise<Result<void>> {
    return this.localMessages.markMessageUnlocked(
      messageId,
      lockDetail,
    );
  }

  // ============ 本地（Dexie）操作 ============

  /** 把一条消息写入本地存储。 */
  async saveMessageToLocal(message: ChatMessage): Promise<Result<void>> {
    return this.localMessages.saveMessage(message);
  }

  /**
   * 批量覆盖写入：先清空本地存储，再写入新列表。
   * 保留 Dart 端的「先清后写」语义（用于同步场景的整批刷新）。
   */
  async saveMessagesToLocal(
    messages: readonly ChatMessage[],
  ): Promise<Result<void>> {
    return this.localMessages.saveMessages(messages);
  }

  /** 读取所有本地消息，按 dbId 升序。 */
  async getLocalMessages(): Promise<Result<ChatMessage[]>> {
    return this.localMessages.getMessages();
  }

  /** 清空本地消息。 */
  async clearLocalMessages(): Promise<Result<void>> {
    return this.localMessages.clearMessages();
  }

  /**
   * 获取本地消息数量。
   * 替代 Dart 的同步 `int get localMessageCount`——Dexie 异步 API 决定必须 async。
   */
  async getLocalMessageCount(): Promise<Result<number>> {
    return this.localMessages.getMessageCount();
  }

  // ============ 本地媒体缓存 ============

  async getCachedMedia(
    input: ChatMediaLookupInput,
  ): Promise<Result<LocalChatMediaRow | null>> {
    return this.mediaCache.getCachedMedia(input);
  }

  async cacheRemoteMedia(
    input: CacheRemoteChatMediaInput,
  ): Promise<Result<LocalChatMediaRow>> {
    return this.mediaCache.cacheRemoteMedia(input);
  }

  async prefetchMediaForMessages(
    messages: readonly ChatMessage[],
  ): Promise<Result<void>> {
    return this.mediaCache.prefetchMediaForMessages(messages);
  }

  async prefetchMediaForSendResponse(
    response: ChatSendResponse,
  ): Promise<Result<void>> {
    return this.mediaCache.prefetchMediaForSendResponse(response);
  }
}

/** 全局懒单例。 */
export const getChatRepository = createLazySingleton<IChatRepository>(
  () =>
    new ChatRepository(
      new ChatRemoteDataSource(chatApi),
      new ChatLocalMessageStore(LocalChatStorage.getInstance()),
      new ChatMediaCacheCoordinator(LocalChatMediaStorage.getInstance()),
    ),
);
