import type { Database } from 'bun:sqlite';

/**
 * Calcula el siguiente display_code disponible entre tareas activas
 * (y tareas completadas en las últimas 24h), empezando en 1 hasta 9999,
 * respetando huecos.
 */
export function pickNextDisplayCode(db: Database): number {
  const MAX_DISPLAY_CODE = 9999;

  const rows = db
    .prepare(`
      SELECT display_code
      FROM tasks
      WHERE display_code IS NOT NULL
        AND (
          COALESCE(completed, 0) = 0
          OR (completed_at IS NOT NULL AND completed_at >= strftime('%Y-%m-%d %H:%M:%f','now','-24 hours'))
        )
      ORDER BY display_code ASC
    `)
    .all() as Array<{ display_code: number }>;

  let expect = 1;
  for (const r of rows) {
    const dc = Number(r.display_code || 0);
    if (dc < expect) continue;
    if (dc === expect) {
      expect++;
      if (expect > MAX_DISPLAY_CODE) break;
      continue;
    }
    // encontrado hueco
    break;
  }
  if (expect > MAX_DISPLAY_CODE) {
    throw new Error('No hay códigos disponibles (límite alcanzado)');
  }
  return expect;
}
