import { existsSync } from "node:fs";
import { resolve, sep } from "node:path";

const root = resolve(process.cwd(), "packages/ui/storybook-static");
const port = Number(process.env.STORYBOOK_STATIC_PORT || 6007);

if (!existsSync(resolve(root, "iframe.html"))) {
  throw new Error(
    "packages/ui/storybook-static is missing. Run bun run build-storybook first.",
  );
}

Bun.serve({
  hostname: "127.0.0.1",
  port,
  async fetch(request) {
    const url = new URL(request.url);
    const pathname = decodeURIComponent(url.pathname);
    const relativePath = pathname === "/" ? "/index.html" : pathname;
    const filePath = resolve(root, `.${relativePath}`);

    if (!filePath.startsWith(`${root}${sep}`)) {
      return new Response("Forbidden", { status: 403 });
    }

    const file = Bun.file(filePath);
    if (!(await file.exists())) {
      return new Response("Not found", { status: 404 });
    }

    return new Response(file);
  },
});

console.log(`Storybook static listening on http://127.0.0.1:${port}`);
