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

import type { Locale } from "./translations";

export const STORAGE_KEYS = {
  authToken: "recorder.authToken",
  backendUrl: "recorder.backendUrl",
  fieldName: "recorder.fieldName",
  language: "recorder.language",
};

export type RecorderSettings = {
  authToken: string;
  backendUrl: string;
  fieldName: string;
  language: Locale;
};

export async function loadRecorderSettings(): Promise<RecorderSettings> {
  const entries = await AsyncStorage.multiGet([
    STORAGE_KEYS.backendUrl,
    STORAGE_KEYS.authToken,
    STORAGE_KEYS.fieldName,
    STORAGE_KEYS.language,
  ]);

  const values = Object.fromEntries(entries);

  return {
    authToken: values[STORAGE_KEYS.authToken] ?? "",
    backendUrl: values[STORAGE_KEYS.backendUrl] ?? "",
    fieldName: values[STORAGE_KEYS.fieldName] ?? "file",
    language: (values[STORAGE_KEYS.language] as Locale) ?? "ca",
  };
}

export async function saveRecorderSettings(settings: RecorderSettings) {
  await AsyncStorage.multiSet([
    [STORAGE_KEYS.backendUrl, settings.backendUrl],
    [STORAGE_KEYS.authToken, settings.authToken],
    [STORAGE_KEYS.fieldName, settings.fieldName || "file"],
    [STORAGE_KEYS.language, settings.language],
  ]);
}
