/**
 * 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 { createDynaBridgeClient } from "../../../utils/ddb";
import { DoorStatus } from "../../../types/DoorStatus";
import { getLockStatusID, isLockOpen } from "../../../schema/LockStatus";

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 db = createDynaBridgeClient(context);
  const lock = await db.entities.lockStatus.findById(getLockStatusID(door));

  const isOpen = isLockOpen(lock);

  if (isOpen && lock) {
    const fingerprint = JSON.parse(lock.fingerprint);

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

    await db.entities.lockStatus.deleteById(getLockStatusID(door));
  } else {
    response
    .setStatusCode(200)
    .appendHeader('Content-Type', 'application/json')
    .setBody({
      status: DoorStatus.CLOSED, 
    });
  }

  // destroy the internal client after
  // @ts-ignore
  db.ddbClient.destroy();
  return callback(null, response);
};
