import Dexie, { type EntityTable } from 'dexie';
import type { Thread, MessageSummary, Folder } from '@/api/client';

type CachedThread = Thread & { folder_id: string; account_id: string };
type CachedMessage = MessageSummary & { thread_id: string; account_id: string };
type CachedFolder = Folder & { account_id: string };

type SyncState = {
  account_id: string;
  last_server_version: number;
  last_sync_at: string;
};

type PendingMutation = {
  id: string;
  account_id: string;
  op: string;
  target_id: string;
  payload: unknown;
  created_at: string;
  attempts: number;
};

class MailDB extends Dexie {
  threads!: EntityTable<CachedThread, 'id'>;
  messages!: EntityTable<CachedMessage, 'id'>;
  folders!: EntityTable<CachedFolder, 'id'>;
  syncState!: EntityTable<SyncState, 'account_id'>;
  pendingMutations!: EntityTable<PendingMutation, 'id'>;

  constructor() {
    super('kuamail');
    this.version(1).stores({
      threads: 'id, folder_id, account_id, last_message_at',
      messages: 'id, thread_id, account_id, date_sent, folder_id',
      folders: 'id, account_id, imap_path',
      syncState: 'account_id',
      pendingMutations: 'id, account_id, created_at',
    });
  }
}

export const db = new MailDB();

export type { CachedThread, CachedMessage, CachedFolder, SyncState, PendingMutation };
