import db, { type CellRecord, type CellMemberRecord } from '@/services/db'
export type { CellRecord, CellMemberRecord }

// ─── Cells ──────────────────────────────────────────────

export async function getCells(): Promise<CellRecord[]> {
  return db.cells.toArray()
}

export async function getCell(id: string): Promise<CellRecord | undefined> {
  return db.cells.get(id)
}

export async function saveCell(c: CellRecord) {
  await db.cells.put(c)
}

export async function deleteCell(id: string) {
  await db.cells.delete(id)
  await db.cell_members.where('cellId').equals(id).delete()
}

export function createCellId(): string {
  return crypto.randomUUID()
}

// ─── Cell Members ─────────────────────────────────────────

export async function getMembers(cellId: string): Promise<CellMemberRecord[]> {
  return db.cell_members.where('cellId').equals(cellId).toArray()
}

export async function addMember(m: CellMemberRecord) {
  await db.cell_members.put(m)
}

export async function removeMember(cellId: string, userId: number) {
  await db.table('cell_members').delete([cellId, userId] as any)
}

export async function getUserCells(userId: number): Promise<CellRecord[]> {
  const members = await db.cell_members.where('userId').equals(userId).toArray()
  const cellIds = members.map(m => m.cellId)
  const cells: CellRecord[] = []
  for (const id of cellIds) {
    const c = await db.cells.get(id)
    if (c) cells.push(c)
  }
  return cells
}

export async function getCellWithMembers(cellId: string): Promise<{ cell: CellRecord | undefined; members: CellMemberRecord[] }> {
  const [cell, members] = await Promise.all([db.cells.get(cellId), db.cell_members.where('cellId').equals(cellId).toArray()])
  return { cell, members }
}

export async function getAllCellsWithCounts(): Promise<(CellRecord & { memberCount: number })[]> {
  const cells = await db.cells.toArray()
  const counts = await db.cell_members.toArray()
  const countMap = new Map<string, number>()
  for (const m of counts) {
    countMap.set(m.cellId, (countMap.get(m.cellId) || 0) + 1)
  }
  return cells.map(c => ({ ...c, memberCount: countMap.get(c.id) || 0 }))
}
