import fs from "fs";
import path from "path";

const IMPERSONATE_RESET_ON_POLL = process.env.IMPERSONATE_RESET_ON_POLL !== "false";
const IMPERSONATE_INDICATOR     = process.env.IMPERSONATE_INDICATOR !== "false";

// realDiscordId → userKey being impersonated
const impersonations = new Map<string, string>();

export function setImpersonation(realDiscordId: string, userKey: string): void {
  impersonations.set(realDiscordId, userKey);
}

export function clearImpersonation(realDiscordId: string): void {
  impersonations.delete(realDiscordId);
}

export function getImpersonation(realDiscordId: string): string | null {
  return impersonations.get(realDiscordId) ?? null;
}

export function clearAllImpersonations(): void {
  if (IMPERSONATE_RESET_ON_POLL) impersonations.clear();
}

export function shouldShowIndicator(): boolean {
  return IMPERSONATE_INDICATOR;
}

// Returns all registered userKeys from usermap.json
export function getRegisteredUsers(): { userKey: string; aliases: string[] }[] {
  try {
    const usermap = JSON.parse(
      fs.readFileSync(path.join(__dirname, "../../data/usermap.json"), "utf8")
    );
    return Object.entries(usermap).map(([, entry]: [string, any]) => {
      const fileKey = typeof entry === "string" ? entry : entry.file;
      const aliases = typeof entry === "object" ? (entry.aliases ?? []) : [];
      return { userKey: fileKey, aliases };
    });
  } catch {
    return [];
  }
}