import { createProjectWorkspace, listProjectFolders } from "./workspaces.js";
import { browseFolders, createBrowsedFolder, registerBrowsedWorkspace } from "./folder-browser.js";
import { readJson } from "./http.js";

export async function resolveWorkspaceRoute(req, url, context) {
  if (req.method === "GET" && url.pathname === "/project-folders") {
    const list = context.listProjectFolders ?? listProjectFolders;
    return { status: 200, body: { projects: await list(context.config) } };
  }

  if (req.method === "GET" && url.pathname === "/folder-browser") {
    const browse = context.browseFolders ?? browseFolders;
    return { status: 200, body: await browse(context.config, url.searchParams.get("folderId") || undefined) };
  }

  if (req.method === "POST" && url.pathname === "/folder-browser/folders") {
    const input = await readJson(req);
    const create = context.createBrowsedFolder ?? createBrowsedFolder;
    return { status: 201, body: await create(context.config, input?.parentId, input?.name) };
  }

  if (req.method === "POST" && url.pathname === "/workspaces") {
    const input = await readJson(req);
    if (input?.folderId) {
      const register = context.registerBrowsedWorkspace ?? registerBrowsedWorkspace;
      return { status: 201, body: await register(context.config, context.configPath, input.folderId) };
    }
    const create = context.createProjectWorkspace ?? createProjectWorkspace;
    return {
      status: 201,
      body: await create(context.config, context.configPath, input)
    };
  }

  return null;
}
