import { serve } from "bun";
import { Hono } from "hono";
import { prettyJSON } from "hono/pretty-json";
import { createDDBClient, getDoorConfigCommand, getLockStatusCommand, isLockOpen } from "../../doorman-api/src/utils/ddb";
import { DoorStatus } from "../../doorman-api/src/types/DoorStatus";

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({
      err: "Must specify a door",
    }, 400);
  }

  const client = createDDBClient(Bun.env as any);
  const config = await client.send(getDoorConfigCommand(door));

  if (!config.Item) {
    return c.json({
      err: "This buzzer is not registered properly",
    }, 404);
  }
  return await client.send(getLockStatusCommand(door))
    .then(async (lock) => {
      const status = isLockOpen(lock) ? DoorStatus.OPEN: "CLOSED";
      return c.json({
        id: door, 
        status, 
      });
    }).catch((e) => {
      console.log(e);
      return c.json({
        err: e,
      }, 500);
    });
});

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