import db, { type SessionRecord, type SessionSummaryRecord, type ProjectStateRecord } from '@/services/db'
export type { SessionRecord, SessionSummaryRecord, ProjectStateRecord }

// ─── Sessions ─────────────────────────────────────────────

export async function saveSession(s: Omit<SessionRecord, 'id'>): Promise<number> {
  return db.sessions.add(s)
}

export async function getSessionsByProject(projectId: number): Promise<SessionRecord[]> {
  return db.sessions.where('projectId').equals(projectId).reverse().sortBy('date')
}

export async function getSession(id: number): Promise<SessionRecord | undefined> {
  return db.sessions.get(id)
}

// ─── Session Summaries ────────────────────────────────────

export async function saveSessionSummary(s: SessionSummaryRecord) {
  await db.session_summaries.put(s)
}

export async function getSessionSummary(sessionId: number): Promise<SessionSummaryRecord | undefined> {
  return db.session_summaries.get(sessionId)
}

export async function getSummariesByProject(projectId: number): Promise<SessionSummaryRecord[]> {
  const sessions = await getSessionsByProject(projectId)
  const ids = sessions.map(s => s.id!).filter(Boolean)
  const summaries: SessionSummaryRecord[] = []
  for (const id of ids) {
    const s = await getSessionSummary(id)
    if (s) summaries.push(s)
  }
  return summaries
}

// ─── Project State ────────────────────────────────────────

export async function saveProjectState(s: ProjectStateRecord) {
  await db.project_state.put(s)
}

export async function getProjectState(projectId: number): Promise<ProjectStateRecord | undefined> {
  return db.project_state.get(projectId)
}

// ─── Helpers ──────────────────────────────────────────────

export async function deleteProjectData(projectId: number) {
  const sessions = await getSessionsByProject(projectId)
  const ids = sessions.map(s => s.id!).filter(Boolean)
  await db.sessions.where('projectId').equals(projectId).delete()
  await db.session_summaries.bulkDelete(ids)
  await db.project_state.delete(projectId)
}

export async function getSessionCount(projectId: number): Promise<number> {
  return db.sessions.where('projectId').equals(projectId).count()
}
