import { TwilioContext } from "../types/TwilioContext";
import { DynaBridge } from "dynabridge";
import { DoorConfigEntity, EditDoorConfigEntity, OnboardDoorConfigEntity } from "../schema/DoorConfig";
import { DoorAliasEntity } from "../schema/DoorAlias";
import { LockStatusEntity } from "../schema/LockStatus";
import { DynamoDBClientConfig } from "@aws-sdk/client-dynamodb";
import { LogCallEntity } from "../schema/LogCall";

export const createDynaBridgeClient = (context: TwilioContext) => {
  let config: DynamoDBClientConfig = {
    region: "us-east-1",
    credentials: {
      accessKeyId: context.AWS_ACCESS_KEY,
      secretAccessKey: context.AWS_SECRET_ACCESS_KEY,
    },
  };

  // for local DDB
  if (context.AWS_ENDPOINT && !context.AWS_ACCESS_KEY && !context.AWS_SECRET_ACCESS_KEY) {
    config = {
      endpoint: context.AWS_ENDPOINT,
    }
  }

  // register all entities here
  return new DynaBridge({
    doorConfig: DoorConfigEntity,
    editDoorConfig: EditDoorConfigEntity,
    doorAlias: DoorAliasEntity,
    lockStatus: LockStatusEntity,
    onboardDoorConfig: OnboardDoorConfigEntity,
    logCall: LogCallEntity
  }, {
    serialize: (entity) => entity,
    deserialize: (entity) => {
      // convert all set to array
      const convertedObj = Object.fromEntries(
        Object.entries(entity).map(([key, value]) => {
          if (value instanceof Set) {
            return [key, Array.from(value)];
          }
          return [key, value];
        })
      );
      return convertedObj;
    }
  }, config);
};
