import { register, Registry, Summary } from "prom-client";
import { InfoResponse } from "../../../doorman-api/src/functions/api/door/info";
import { TwilioContext } from "../types/TwilioContext";
import { lambdaFastHttp } from "./LambdaUtils";
import { BuzzerActivatedMetrics } from "../metrics/BuzzerActivatedMetrics";
import { ONBOARDING_DOOR_NAME } from "../../../doorman-api/src/schema/DoorConfig";
import { LogCallResponse } from "../../../doorman-api/src/functions/api/door/logCall";

export async function getConfig(context: TwilioContext, buzzer: string): Promise<InfoResponse | undefined> {
  return await fetch(context.DOORMAN_URL + `/api/door/info?buzzer=${buzzer}`)
    .then(res => res.json())
    .catch(err => {
      return undefined;
    }) as InfoResponse;
}

export async function tryLogCallerForOnboarding(context: TwilioContext, caller: string): Promise<LogCallResponse> {
  return await fetch(context.DOORMAN_URL + `/api/door/logCall?caller=${caller}`)
    .then(res => res.json())
    .catch(err => {
      return undefined;
    }) as LogCallResponse;
}

export async function notifyDiscord(context: TwilioContext, msg: string[], u: string[], optionalJsonStr: string[], metricsRegistry: Registry) {
  const endTimer = (metricsRegistry.getSingleMetric(BuzzerActivatedMetrics.NOTIFY_LATENCY) as Summary).startTimer();
  const res = await lambdaFastHttp(context.DOORMAN_URL +
    `/api/door/notify?discordUser=${encodeURIComponent(JSON.stringify(u))}&msg=${encodeURIComponent(JSON.stringify(msg))}&json=${encodeURIComponent(JSON.stringify(optionalJsonStr))}&key=${context.NOTIFY_SECRET_KEY}`,
  ).catch(err => console.log(err));
  endTimer();
  return res;
}

export async function notifyAllDiscord(context: TwilioContext, config: InfoResponse, msg: string, metricsRegistry: Registry, optionalJsonStr: string = "") {
  return notifyDiscord(context, config.discordUsers.map(() => msg), config.discordUsers, config.discordUsers.map(() => optionalJsonStr), metricsRegistry);
}