import { Context } from "aws-lambda";
import { Iot, IotData } from "aws-sdk";
import {} from "../errors";
import { initCommonMiddlewares } from "../middlewares";

interface IEvent {
  user: {
    username: string;
  };
  pub: object;
}

interface IResult {}

const { TOPIC_PREFIX } = process.env;

const iot = new Iot();

let cachedEndpointAddress: string = null;

async function awsHandler(event: IEvent, context: Context): Promise<IResult> {
  const { user, pub } = event;

  if (cachedEndpointAddress === null) {
    // Use runtime context to cache endpoint-address
    const { endpointAddress } = await iot.describeEndpoint().promise();
    cachedEndpointAddress = endpointAddress;
  }

  const iotData = new IotData({ endpoint: cachedEndpointAddress });

  await iotData
    .publish({
      topic: `${TOPIC_PREFIX}/${user.username}`,
      payload: JSON.stringify(pub),
    })
    .promise();

  return {};
}

export const handler = initCommonMiddlewares(awsHandler);
