"use client";

/**
 * Dexie 数据库定义
 *
 * 唯一表 `messages`，只有 `++dbId` 自增主键，无次级索引（按本轮需求"最简表"）。
 * 未来要按 session 查询可升级到：
 *   this.version(2).stores({ messages: "++dbId, sessionId, createdAt" })
 *   .upgrade(async (tx) => { ... });
 *
 * 构造时 `dbName` 可注入，便于测试时每个用例用独立 DB 互不污染。
 */

import Dexie, { type Table } from "dexie";
import type { ChatMediaKind } from "@/data/dto/chat";
import type {
  ChatImageData,
  ChatLockDetailData,
} from "@/data/schemas/chat";

export interface LocalMessageRow {
  /** Dexie 自增主键（数据库内部使用，不暴露给 LocalMessage 类）。 */
  dbId?: number;
  /** 消息 id（来自 ChatMessage.id）。 */
  id: string;
  role: string;
  type: string;
  content: string;
  createdAt: string;
  audioUrl?: string | null;
  image?: ChatImageData;
  lockDetail?: ChatLockDetailData;
  sessionId: string;
}

export interface LocalChatMediaRow {
  cacheKey: string;
  ownerKey: string;
  messageId: string;
  kind: ChatMediaKind;
  remoteUrl: string;
  blob: Blob;
  mimeType: string;
  byteSize: number;
  createdAt: number;
  updatedAt: number;
  lastAccessedAt: number;
}

export class LocalChatDB extends Dexie {
  messages!: Table<LocalMessageRow, number>;
  media!: Table<LocalChatMediaRow, string>;

  constructor(dbName: string = "cozsweet-chat") {
    super(dbName);
    this.version(1).stores({
      messages: "++dbId",
    });
    this.version(2).stores({
      messages: "++dbId",
      media: "cacheKey, ownerKey, messageId, kind, remoteUrl, updatedAt, lastAccessedAt",
    });
  }
}
