import {
  handleClientAssetRequest,
  isClientAssetPath
} from "./client-assets.js";
import { htmlPage } from "./page-template.js";
import {
  handleNextcloudBlobRequest,
  handleNextcloudListRequest
} from "./nextcloud-proxy.js";
import type { IncomingMessage, ServerResponse } from "node:http";

export function createRequestHandler() {
  return async function handleRequest(req: IncomingMessage, res: ServerResponse) {
    const url = new URL(req.url ?? "/", "http://localhost");

    if (url.pathname === "/health") {
      res.statusCode = 200;
      res.setHeader("content-type", "application/json; charset=utf-8");
      res.end(JSON.stringify({ status: "ok" }));
      return;
    }

    if (isClientAssetPath(url.pathname)) {
      await handleClientAssetRequest(url, res);
      return;
    }

    if (url.pathname === "/api/nextcloud/list") {
      await handleNextcloudListRequest(url, res);
      return;
    }

    if (url.pathname === "/api/nextcloud/blob") {
      await handleNextcloudBlobRequest(url, res);
      return;
    }

    res.statusCode = 200;
    res.setHeader("content-type", "text/html; charset=utf-8");
    res.end(htmlPage());
  };
}
