/**
 * Server-side ePay session store (global singleton).
 * Separate from eTerra session — different auth system.
 */

type EpaySession = {
  username: string;
  password: string;
  connectedAt: string;
  credits: number;
  creditsCheckedAt: string;
};

const g = globalThis as { __epaySession?: EpaySession | null };

export function createEpaySession(
  username: string,
  password: string,
  credits: number,
): void {
  g.__epaySession = {
    username,
    password,
    connectedAt: new Date().toISOString(),
    credits,
    creditsCheckedAt: new Date().toISOString(),
  };
}

export function destroyEpaySession(): void {
  g.__epaySession = null;
}

export function getEpayCredentials(): {
  username: string;
  password: string;
} | null {
  const session = g.__epaySession;
  if (!session) return null;
  return { username: session.username, password: session.password };
}

export function getEpaySessionStatus(): {
  connected: boolean;
  username?: string;
  connectedAt?: string;
  credits?: number;
  creditsCheckedAt?: string;
} {
  const session = g.__epaySession;
  if (!session) return { connected: false };
  return {
    connected: true,
    username: session.username,
    connectedAt: session.connectedAt,
    credits: session.credits,
    creditsCheckedAt: session.creditsCheckedAt,
  };
}

export function updateEpayCredits(credits: number): void {
  if (g.__epaySession) {
    g.__epaySession.credits = credits;
    g.__epaySession.creditsCheckedAt = new Date().toISOString();
  }
}
