import { serve } from "bun";
import { Hono } from "hono";
import { prettyJSON } from "hono/pretty-json";
import { createDynaBridgeClient } from "../../doorman-api/src/utils/ddb";
import { DoorStatus } from "../../doorman-api/src/types/DoorStatus";
import { getLockStatusID, isLockOpen } from "../../doorman-api/src/schema/LockStatus";
import { getDoorConfigID } from "../../doorman-api/src/schema/DoorConfig";

const app = new Hono();

app.use(prettyJSON());

app.get("/api/door/info", async (c) => {
  const door = c.req.query().door;
  if (!door) {
    return c.json({
      msg: "Must specify a door",
    }, 400);
  }

  const db = createDynaBridgeClient(Bun.env as any);

  const config = await db.entities.doorConfig.findById(getDoorConfigID(door));
  console.log(config);


  if (!config) {
    return c.json({
      msg: "This buzzer is not registered properly",
    }, 404);
  }

  const lock = await db.entities.lockStatus.findById(getLockStatusID(door));
  const status = isLockOpen(lock) ? DoorStatus.OPEN : "CLOSED";
  return c.json({
    id: door,
    status,
  });
});

serve({
  fetch: app.fetch,
});
