import { saveLookup, getLookups } from '@/services/users-db'

export interface StatusDef {
  id: number
  name: string
  description: string
}

const STATUSES: StatusDef[] = [
  { id: 1, name: 'Por hacer', description: 'Tarea pendiente por iniciar' },
  { id: 2, name: 'En progreso', description: 'Tarea actualmente en desarrollo' },
  { id: 3, name: 'En revisión', description: 'Tarea en proceso de revisión' },
  { id: 4, name: 'En pruebas', description: 'Tarea en fase de pruebas' },
  { id: 5, name: 'Completado', description: 'Tarea finalizada' },
  { id: 6, name: 'Bloqueado', description: 'Tarea bloqueada por dependencias' },
  { id: 7, name: 'Cancelado', description: 'Tarea cancelada definitivamente' },
]

const STATUS_MAP: Record<string, number> = {
  '1': 1,
  'todo': 1,
  'por hacer': 1,
  'not started': 1,
  '2': 2,
  'in_progress': 2,
  'doing': 2,
  'wip': 2,
  'active': 2,
  'in progress': 2,
  'en progreso': 2,
  'true': 2,
  '3': 3,
  'review': 3,
  'revisión': 3,
  'qa-ready': 3,
  '4': 4,
  'testing': 4,
  'pruebas': 4,
  'qa-testing': 4,
  '5': 5,
  'done': 5,
  'completed': 5,
  'closed': 5,
  'finalizado': 5,
  '6': 6,
  'blocked': 6,
  'bloqueado': 6,
  'ready to deploy': 6,
  'qa-client': 6,
  '7': 7,
  'cancelled': 7,
  'cancelado': 7,
  'false': 1,
}

let cachedStatuses: Map<number, StatusDef> | null = null

export function resolveStatusName(raw: unknown): string {
  const str = raw != null ? String(raw).trim().toLowerCase() : ''
  if (!str) return 'Por hacer'
  const id = STATUS_MAP[str]
  if (!id) return String(raw)
  const def = STATUSES.find(s => s.id === id)
  return def?.name ?? String(raw)
}

export function resolveStatusId(raw: unknown): number {
  const str = raw != null ? String(raw).trim().toLowerCase() : ''
  if (!str) return 1
  return STATUS_MAP[str] ?? 1
}

export async function seedStatusLookups(): Promise<void> {
  for (const s of STATUSES) {
    await saveLookup('status', s.id, s.name, s.description)
  }
  cachedStatuses = new Map(STATUSES.map(s => [s.id, s]))
}

export async function loadStatusLookups(): Promise<StatusDef[]> {
  const records = await getLookups('status')
  if (records.length > 0) {
    cachedStatuses = new Map(records.map(r => [r.id, { id: r.id, name: r.name, description: r.description ?? '' }]))
    return Array.from(cachedStatuses.values())
  }
  return STATUSES
}

export function getCachedStatuses(): StatusDef[] {
  if (cachedStatuses) return Array.from(cachedStatuses.values())
  return STATUSES
}
