import type { Database } from 'bun:sqlite';
import { ensureUserExists } from '../../../db';

type Ctx = {
  sender: string;
  groupId: string;
  message: string;
};

type Msg = {
  recipient: string;
  message: string;
  mentions?: string[];
};

export function handleAlarma(context: Ctx, deps: { db: Database }): Msg[] {
  const tokens = (context.message || '').trim().split(/\s+/);

  const optRaw = (tokens[2] || '').toLowerCase();
  const map: Record<string, 'daily' | 'weekly' | 'off' | 'weekdays'> = {
    'daily': 'daily',
    'diario': 'daily',
    'diaria': 'daily',
    'l-v': 'weekdays',
    'lv': 'weekdays',
    'laborables': 'weekdays',
    'weekdays': 'weekdays',
    'semanal': 'weekly',
    'weekly': 'weekly',
    'off': 'off',
    'apagar': 'off',
    'ninguno': 'off'
  };
  const freq = map[optRaw];

  // Hora opcional HH:MM
  const timeRaw = tokens[3] || '';
  let timeNorm: string | null = null;
  if (timeRaw) {
    const m = /^(\d{1,2}):([0-5]\d)$/.exec(timeRaw);
    if (!m) {
      return [{
        recipient: context.sender,
        message: 'ℹ️ Uso: `t alarma diario|l-v|semanal|off [HH:MM]`'
      }];
    }
    const hh = Math.max(0, Math.min(23, parseInt(m[1], 10)));
    timeNorm = `${String(hh).padStart(2, '0')}:${m[2]}`;
  }

  if (!freq) {
    return [{
      recipient: context.sender,
      message: 'ℹ️ Uso: `t alarma diario|l-v|semanal|off [HH:MM]`'
    }];
  }

  const ensured = ensureUserExists(context.sender, deps.db);
  if (!ensured) {
    throw new Error('No se pudo asegurar el usuario');
  }

  deps.db.prepare(`
        INSERT INTO user_preferences (user_id, reminder_freq, reminder_time, last_reminded_on, updated_at)
        VALUES (?, ?, COALESCE(?, COALESCE((SELECT reminder_time FROM user_preferences WHERE user_id = ?), '08:30')), NULL, strftime('%Y-%m-%d %H:%M:%f', 'now'))
        ON CONFLICT(user_id) DO UPDATE SET
          reminder_freq = excluded.reminder_freq,
          reminder_time = CASE WHEN ? IS NOT NULL THEN excluded.reminder_time ELSE reminder_time END,
          updated_at = excluded.updated_at
      `).run(ensured, freq, timeNorm, ensured, timeNorm);

  let label: string;
  if (freq === 'daily') {
    label = timeNorm ? `diario (${timeNorm})` : 'diario';
  } else if (freq === 'weekdays') {
    label = timeNorm ? `laborables (lunes a viernes ${timeNorm})` : 'laborables (lunes a viernes)';
  } else if (freq === 'weekly') {
    label = timeNorm ? `semanal (lunes ${timeNorm})` : 'semanal (lunes 08:30)';
  } else {
    label = 'apagado';
  }

  return [{
    recipient: context.sender,
    message: `✅ Recordatorios: ${label}`
  }];
}
