/**
 * storage-adapter.ts
 *
 * Capa unificada que enruta a Turso (Tauri) o Dexie (browser).
 * Los consumidores importan desde aquí en vez de tauri-db directo.
 */

import { isTauri } from '@/services/storage-router'
import { tauriDb, type HuDraftRecord as TauriDraft, type AlphaUserRecord, type CellRecord } from '@/services/tauri-db'
import * as dexieDrafts from '@/services/hu-drafts-db'
import * as dexieUsers from '@/services/users-db'

// ─── HuDrafts ───────────────────────────────────────────

export async function getHuDrafts(projectId: number): Promise<any[]> {
  if (isTauri()) {
    const res = await tauriDb.getHuDrafts(projectId)
    return (res || []) as any[]
  }
  return dexieDrafts.getDrafts(projectId)
}

export async function saveHuDraft(draft: any): Promise<void> {
  if (isTauri()) {
    await tauriDb.saveHuDraft(draft as TauriDraft)
  }
  await dexieDrafts.saveDraft(draft)
}

export async function deleteHuDraft(id: string): Promise<void> {
  if (isTauri()) { await tauriDb.deleteHuDraft(id).catch(() => {}) }
  await dexieDrafts.deleteDraft(id)
}

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

export async function getUsers(): Promise<AlphaUserRecord[]> {
  if (isTauri()) {
    const res = await tauriDb.getUsers()
    return (res || []) as AlphaUserRecord[]
  }
  const dbUsers = await dexieUsers.getUsers()
  return dbUsers.map(u => ({
    id: u.id,
    email: u.email,
    first_name: u.firstName,
    last_name: u.lastName,
    role: null,
    seniority: u.seniority,
    cell_id: u.cellId,
    is_active: u.isActive,
    created_at: u.createdAt,
  }) as AlphaUserRecord)
}

export async function saveUser(user: AlphaUserRecord): Promise<void> {
  if (isTauri()) { await tauriDb.saveUser(user).catch(() => {}) }
  await dexieUsers.saveUser({
    id: user.id,
    email: user.email,
    firstName: user.first_name,
    lastName: user.last_name,
    fullName: `${user.first_name} ${user.last_name}`.trim(),
    username: null,
    isActive: user.is_active,
    isStaff: false,
    roleId: null,
    cellId: user.cell_id,
    seniority: user.seniority,
    companyId: null,
    phone: null,
    position: null,
    lastActive: null,
    createdAt: user.created_at || null,
    updatedAt: new Date().toISOString(),
  })
}

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

export async function getCells(): Promise<CellRecord[]> {
  if (isTauri()) {
    const res = await tauriDb.getCells()
    return (res || []) as CellRecord[]
  }
  const items = await dexieUsers.getLookups('cell')
  return items.map(c => ({ id: c.id, name: c.name, description: c.description, created_at: null }) as CellRecord)
}

export async function saveCell(name: string, description?: string): Promise<number> {
  if (isTauri()) {
    return tauriDb.saveCell({ id: 0, name, description: description ?? null, created_at: null })
  }
  const items = await dexieUsers.getLookups('cell')
  const maxId = items.reduce((m, c) => Math.max(m, c.id), 0)
  const newId = maxId + 1
  await dexieUsers.saveLookup('cell', newId, name, description)
  return newId
}

export { type CellRecord } from '@/services/tauri-db'
