import Dexie, { type EntityTable } from 'dexie';
import type { MessageNewService, ReactionGroup } from '@/socket';

/** Message stored in local IndexedDB, enriched with local-only fields. */
export interface CachedMessage extends Omit<MessageNewService, 'room' | 'sender' | 'reactions'> {
  roomId: string;
  senderId: string;
  senderName: string;
  senderAvatar: string;
  edited_at?: string;
  _localReactions: ReactionGroup[];
  _isStreaming: boolean;
  _thinkingContent: string | null;
}

export interface RoomSyncMeta {
  roomId: string;
  maxSeq: number;
  minSeq: number;
  gaps: Array<[number, number]>;
  lastActive: number;
  serverRuntimeId?: string;
}

const db = new Dexie('gitdataai_channel') as Dexie & {
  messages: EntityTable<CachedMessage, 'id'>;
  roomSyncMeta: EntityTable<RoomSyncMeta, 'roomId'>;
};

db.version(1).stores({
  messages: 'id, [roomId+seq], roomId, seq, send_at',
  roomSyncMeta: 'roomId',
});

export { db };
