export type VariableContext = {
  user: string;
  username: string;
  streamer: string;
  channel: string;
  target?: string;
  message?: string;
  count?: number;
  points?: number;
  level?: number;
  rank?: number;
  lastFollower?: string;
  lastSubscriber?: string;
  now?: Date;
};

export const resolveVariables = (template: string, context: VariableContext, random = Math.random): string => {
  const now = context.now ?? new Date();
  const values: Record<string, string> = {
    user: context.user,
    username: context.username,
    streamer: context.streamer,
    channel: context.channel,
    target: context.target ?? "",
    message: context.message ?? "",
    count: String(context.count ?? 0),
    points: String(context.points ?? 0),
    level: String(context.level ?? 1),
    rank: String(context.rank ?? 0),
    date: now.toLocaleDateString("fr-FR"),
    time: now.toLocaleTimeString("fr-FR", { hour: "2-digit", minute: "2-digit" }),
    lastFollower: context.lastFollower ?? "",
    lastSubscriber: context.lastSubscriber ?? ""
  };
  const withRandom = template.replace(/\{random:(-?\d+):(-?\d+)\}/g, (_, first: string, second: string) => {
    const low = Math.min(Number(first), Number(second));
    const high = Math.max(Number(first), Number(second));
    return String(Math.floor(random() * (high - low + 1)) + low);
  });
  return withRandom.replace(/\{([A-Za-z]+)\}/g, (whole, key: string) =>
    Object.hasOwn(values, key) ? (values[key] ?? whole) : whole
  );
};
