/**
 * Try to get buzzer number for a given OTP
 */

import { ServerlessEventObject, ServerlessFunctionSignature } from "@twilio-labs/serverless-runtime-types/types";
import { TwilioContext } from "../../../types/TwilioContext";
import { createDynaBridgeClient } from "../../../utils/ddb";
import { withMetrics } from "../../../common/DoormanHandler";
import { z } from "zod";
import { UserAgentHeader } from "../../../utils/blockUserAgent";
import { setResponseJson } from "../../../utils/responseUtils";
import { getLogCallID } from "../../../schema/LogCall";
import { isTTLInFuture } from "../../../common/TTLHelper";

export const CheckOtpRequestSchema = z.object({
  otp: z.string(),
});

export type CheckOtpRequest = z.infer<typeof CheckOtpRequestSchema>;
export interface CheckOtpRequestTwilio extends ServerlessEventObject<CheckOtpRequest, UserAgentHeader> { };

export const CheckOtpResponseSchema = z.object({
  buzzer: z.string(),
});

export type CheckOtpResponse = z.infer<typeof CheckOtpResponseSchema>;

export const handler: ServerlessFunctionSignature<TwilioContext, CheckOtpRequestTwilio> = withMetrics("checkotp", async (context, event, callback, metricsRegistry) => {
  const response = new Twilio.Response();
  const req = CheckOtpRequestSchema.parse(event);

  let otp = req.otp;

  const db = createDynaBridgeClient(context);

  const log = await db.entities.logCall.findById(getLogCallID(otp));

  if (!log || !isTTLInFuture(log)) {
    setResponseJson(response, 404, {
      msg: "OTP expired or not found",
    })
  } else {
    setResponseJson(response, 200, {
      buzzer: log.caller,
    });
  }

  // destroy the internal client after
  // @ts-ignore
  db.ddbClient.destroy();

  return callback(null, response);
});
