/**
 * authStore.ts — login + persistent SIP credential storage.
 *
 * Closes the loop with PushService (which imports getStoredSipConfig): after the
 * engineer logs in once, the config is persisted so a VoIP push can wake the app
 * and re-REGISTER with NO user interaction, even after the app was killed.
 *
 * Two login modes are supported:
 *   - direct:  engineer types server / extension / password (works out-of-box
 *              with the pjsip.conf we shipped)
 *   - api:     engineer types company creds; backend returns short-lived SIP
 *              secret. Swap loginWithApi() in when your backend is ready.
 */
import AsyncStorage from '@react-native-async-storage/async-storage';
import { SipConfig, buildConfig, DEFAULT_ICE } from '../config';

const KEY = 'ephone.sipconfig.v1';

let cached: SipConfig | null = null;

export async function getStoredSipConfig(): Promise<SipConfig | null> {
  if (cached) return cached;
  const raw = await AsyncStorage.getItem(KEY);
  if (!raw) return null;
  cached = JSON.parse(raw) as SipConfig;
  return cached;
}

export async function saveSipConfig(cfg: SipConfig): Promise<void> {
  cached = cfg;
  await AsyncStorage.setItem(KEY, JSON.stringify(cfg));
}

export async function clearSipConfig(): Promise<void> {
  cached = null;
  await AsyncStorage.removeItem(KEY);
}

export interface DirectLoginInput {
  wsServer: string;    // wss://pbx.yourdomain.com:8089/ws
  domain: string;      // pbx.yourdomain.com
  extension: string;   // 6001
  password: string;
  displayName: string;
}

/** Direct login — validate & persist the SIP profile the engineer typed. */
export async function loginDirect(input: DirectLoginInput): Promise<SipConfig> {
  const cfg = buildConfig({
    wsServer: input.wsServer.trim(),
    domain: input.domain.trim(),
    extension: input.extension.trim(),
    password: input.password,
    displayName: input.displayName.trim() || `Ext ${input.extension.trim()}`,
    iceServers: DEFAULT_ICE,
  });
  await saveSipConfig(cfg);
  return cfg;
}

/**
 * API login (recommended for production) — exchange company creds for a
 * short-lived SIP secret so passwords never live on the device long-term.
 */
export async function loginWithApi(email: string, pass: string): Promise<SipConfig> {
  const res = await fetch('https://api.yourdomain.com/auth/sip-credentials', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ email, password: pass }),
  });
  if (!res.ok) throw new Error('Invalid credentials');
  const data = await res.json(); // { wsServer, domain, extension, password, displayName, iceServers }
  const cfg = buildConfig({ ...data, iceServers: data.iceServers || DEFAULT_ICE });
  await saveSipConfig(cfg);
  return cfg;
}
