import * as SecureStore from "expo-secure-store";
import type { MobileConfig } from "../types/mobileConfig";

// Registre local des instances deja configurees, pour qu'un technicien qui
// travaille pour plusieurs entreprises puisse rebasculer entre elles sans
// re-scanner le QR / retenir un lien, et sans retaper son email.
const SAVED_INSTANCES_KEY = "mf_saved_instances";

export type SavedInstance = {
  base_url: string;
  app_name: string;
  primary_color: string;
  logo_url: string | null;
  tenant_id: string | number | null;
  support_email?: string | null;
  support_phone?: string | null;
  last_email?: string | null;
  saved_at: string;
};

export async function listInstances(): Promise<SavedInstance[]> {
  const raw = await SecureStore.getItemAsync(SAVED_INSTANCES_KEY);
  if (!raw) {
    return [];
  }
  try {
    const parsed = JSON.parse(raw);
    return Array.isArray(parsed) ? (parsed as SavedInstance[]) : [];
  } catch {
    return [];
  }
}

// Ajoute ou met a jour une instance (merge par base_url). Renvoie la liste a
// jour (instance touchee remontee en tete pour un acces rapide).
export async function upsertInstance(
  entry: Partial<SavedInstance> & { base_url: string }
): Promise<SavedInstance[]> {
  const list = await listInstances();
  const existing = list.find((i) => i.base_url === entry.base_url);
  const merged: SavedInstance = {
    base_url: entry.base_url,
    app_name: entry.app_name ?? existing?.app_name ?? "",
    primary_color: entry.primary_color ?? existing?.primary_color ?? "#1e56a8",
    logo_url: entry.logo_url ?? existing?.logo_url ?? null,
    tenant_id: entry.tenant_id ?? existing?.tenant_id ?? null,
    support_email: entry.support_email ?? existing?.support_email ?? null,
    support_phone: entry.support_phone ?? existing?.support_phone ?? null,
    last_email: entry.last_email ?? existing?.last_email ?? null,
    saved_at: entry.saved_at ?? existing?.saved_at ?? "",
  };
  const rest = list.filter((i) => i.base_url !== entry.base_url);
  const next = [merged, ...rest];
  await SecureStore.setItemAsync(SAVED_INSTANCES_KEY, JSON.stringify(next));
  return next;
}

export async function removeInstance(baseUrl: string): Promise<SavedInstance[]> {
  const list = await listInstances();
  const next = list.filter((i) => i.base_url !== baseUrl);
  await SecureStore.setItemAsync(SAVED_INSTANCES_KEY, JSON.stringify(next));
  return next;
}

// Construit une MobileConfig a partir d'une instance enregistree (fallback
// hors-ligne quand on ne peut pas re-fetcher la config a jour).
export function configFromInstance(entry: SavedInstance): MobileConfig {
  return {
    app_name: entry.app_name,
    primary_color: entry.primary_color,
    logo_url: entry.logo_url,
    tenant_id: entry.tenant_id,
    support_email: entry.support_email ?? null,
    support_phone: entry.support_phone ?? null,
  };
}
