import { jsonResponse, corsHeaders } from "../lib/http";
import { normalizePath } from "../lib/slug";
import { handleConfigGet } from "./routes/config";
import { handleAdminSessionPost } from "./routes/admin-session";
import {
  handlePostsCollection,
  handlePostItem
} from "./routes/posts";

export async function handleApi(request: Request, env: Env): Promise<Response> {
  if (!env.DB) {
    return jsonResponse({ ok: false, error: "db_not_configured" }, 500);
  }

  if (request.method === "OPTIONS") {
    return new Response(null, { headers: corsHeaders() });
  }

  const url = new URL(request.url);
  const path = normalizePath(url.pathname);
  const segments = path.split("/").filter(Boolean);

  if (segments[0] !== "api") {
    return jsonResponse({ ok: false, error: "Not found" }, 404);
  }

  const parts = segments.slice(1);

  if (
    parts[0] === "config" &&
    parts.length === 1 &&
    request.method === "GET"
  ) {
    return handleConfigGet(env);
  }

  if (
    parts[0] === "admin" &&
    parts[1] === "session" &&
    parts.length === 2 &&
    request.method === "POST"
  ) {
    return handleAdminSessionPost(request, env);
  }

  if (parts[0] === "posts") {
    if (parts.length === 1) {
      return handlePostsCollection(request, env, url);
    }
    if (parts.length === 2) {
      return handlePostItem(request, env, url, parts[1]);
    }
  }

  return jsonResponse({ ok: false, error: "Not found" }, 404);
}
