import { normalizeTime } from '$lib/server/datetime';

/**
 * Resolves the reminder time to save based on frequency and raw input.
 * Returns { timeToSave } on success or { error } on validation failure.
 * Callers must handle the error case with their own Response/fail mechanism.
 */
export function resolveReminderTime(
  db: any,
  userId: string,
  freqRaw: string,
  timeRaw: string | null
): { timeToSave: string } | { error: string } {
  if (freqRaw === 'off') {
    // Hora opcional: si viene, validar/normalizar; si no, conservar la actual o usar '08:30'
    if (timeRaw && timeRaw.length > 0) {
      const norm = normalizeTime(timeRaw);
      if (!norm) return { error: 'hora inválida' };
      return { timeToSave: norm };
    }
    const row = db
      .prepare(
        `SELECT reminder_time AS time
         FROM user_preferences
         WHERE user_id = ?
         LIMIT 1`
      )
      .get(userId) as any;
    return { timeToSave: row?.time ? String(row.time) : '08:30' };
  }

  // daily/weekly/weekdays: si no se especifica hora, usar '08:30'
  if (!timeRaw || timeRaw.length === 0) {
    return { timeToSave: '08:30' };
  }
  const norm = normalizeTime(timeRaw);
  if (!norm) return { error: 'hora inválida' };
  return { timeToSave: norm };
}

/** SQL for upserting user preferences (preserves last_reminded_on). */
export function upsertPreference(
  db: any,
  userId: string,
  freqRaw: string,
  timeToSave: string
): void {
  db.prepare(
    `INSERT INTO user_preferences (user_id, reminder_freq, reminder_time, last_reminded_on, updated_at)
     VALUES (?, ?, ?, (SELECT last_reminded_on FROM user_preferences WHERE user_id = ?), strftime('%Y-%m-%d %H:%M:%f','now'))
     ON CONFLICT(user_id) DO UPDATE SET
       reminder_freq = excluded.reminder_freq,
       reminder_time = excluded.reminder_time,
       updated_at = excluded.updated_at`
  ).run(userId, freqRaw, timeToSave, userId);
}
