import db, { type UserRecord, type LookupRecord } from '@/services/db'
export type { UserRecord, LookupRecord }

// ─── Users ───────────────────────────────────────────────

export async function saveUser(u: UserRecord) {
  await db.users.put(u)
}

export async function getUsers(): Promise<UserRecord[]> {
  return db.users.toArray()
}

export async function getUser(id: number): Promise<UserRecord | undefined> {
  return db.users.get(id)
}

export async function deleteUser(id: number) {
  await db.users.delete(id)
}

// ─── Lookups ─────────────────────────────────────────────

export async function saveLookup(type: string, id: number, name: string, description?: string) {
  await db.lookups.put({ type, id, name, description: description ?? null })
}

export async function getLookups(type: string): Promise<LookupRecord[]> {
  return db.lookups.where('type').equals(type).toArray()
}

export async function getLookup(type: string, id: number): Promise<LookupRecord | undefined> {
  return db.lookups.get([type, id])
}

export async function lookupsAsOptions(type: string): Promise<{ value: number; label: string }[]> {
  const items = await getLookups(type)
  return items.map(i => ({ value: i.id, label: i.name }))
}
