/**
 * Try to update door status
 */

import { ServerlessFunctionSignature, ServerlessEventObject } from "@twilio-labs/serverless-runtime-types/types";
import { TwilioContext } from "../../../types/TwilioContext";
import { shouldBlockRequest } from "../../../utils/blockUserAgent";
import { clearLockStatusCommand, createDDBClient, getLockStatusCommand, isLockOpen } from "../../../utils/ddb";
import { DoorStatus } from "../../../types/DoorStatus";

export interface StatusRequest extends ServerlessEventObject {
  door: string;
}

export interface StatusResponse {
  status: DoorStatus, 
  fingerprint: any;
}

export const handler: ServerlessFunctionSignature<TwilioContext, StatusRequest> = async function(context, event, callback) {
  const response = new Twilio.Response();

  if (shouldBlockRequest(event)) {
    response.setStatusCode(200);
    return callback(null, response);
  }

  const door = event.door;

  if (!door) {
    response.setStatusCode(400);
    return callback(null, response);
  }

  const client = createDDBClient(context);

  await client.send(getLockStatusCommand(door))
    .then(async (lock) => {
      const isOpen = isLockOpen(lock);

      if (isOpen) {
        const fingerprint = JSON.parse(lock?.Item?.fingerprint.S as string);

        response
          .setStatusCode(200)
          .appendHeader('Content-Type', 'application/json')
          .setBody({
            status: DoorStatus.OPEN,
            fingerprint,
          });

        await client.send(clearLockStatusCommand(lock));
        return;
      }

      response
        .setStatusCode(200)
        .appendHeader('Content-Type', 'application/json')
        .setBody({
          status: DoorStatus.CLOSED, 
        });

    }).catch((e) => {
      console.log(e);
      response
        .setStatusCode(500)
        .appendHeader('Content-Type', 'application/json')
        .setBody({ err: e });
    });

  await client.destroy();
  return callback(null, response);
};
