import AsyncStorage from '@react-native-async-storage/async-storage';

/**
 * How many minutes before a session's expiry to fire the local reminder.
 * Configurable in Notifications preferences, in 5-minute increments.
 */
const KEY = 'ps_reminder_lead_minutes';
export const DEFAULT_LEAD_MINUTES = 15;
export const MIN_LEAD_MINUTES = 5;
export const MAX_LEAD_MINUTES = 60;
export const LEAD_STEP = 5;

/** When true, expiry reminders are enabled at all. */
const ENABLED_KEY = 'ps_reminder_enabled';

export async function getReminderLeadMinutes(): Promise<number> {
  const raw = await AsyncStorage.getItem(KEY);
  const n = raw != null ? parseInt(raw, 10) : NaN;
  return Number.isFinite(n) ? n : DEFAULT_LEAD_MINUTES;
}

export async function setReminderLeadMinutes(minutes: number): Promise<void> {
  const clamped = Math.min(
    MAX_LEAD_MINUTES,
    Math.max(MIN_LEAD_MINUTES, Math.round(minutes / LEAD_STEP) * LEAD_STEP),
  );
  await AsyncStorage.setItem(KEY, String(clamped));
}

export async function getRemindersEnabled(): Promise<boolean> {
  const raw = await AsyncStorage.getItem(ENABLED_KEY);
  return raw == null ? true : raw === 'true';
}

export async function setRemindersEnabled(on: boolean): Promise<void> {
  await AsyncStorage.setItem(ENABLED_KEY, String(on));
}
