import type { DevToolbarCollector } from "./collector.ts";
import { DEV_TOOLBAR_CSS, DEV_TOOLBAR_RUNTIME } from "../client/index.ts";
import { openInEditor } from "./editor.ts";
import { serializeDevToolbarJson } from "./serialize.ts";
import type { DevToolbarPanel, DevToolbarPlatformSnapshot } from "../types.ts";

export interface DevToolbarRouteOptions {
  mode: string;
  root: string;
  collector: DevToolbarCollector;
  editor?: string;
  allowOpenEditor?: boolean;
  platform?: DevToolbarPlatformSnapshot;
  panels?: DevToolbarPanel[] | (() => DevToolbarPanel[] | Promise<DevToolbarPanel[]>);
}

const json = (value: unknown, status = 200) =>
  new Response(serializeDevToolbarJson(value), {
    status,
    headers: { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" },
  });

export async function handleDevToolbarRoute(
  request: Request,
  options: DevToolbarRouteOptions,
): Promise<Response | null> {
  const url = new URL(request.url);
  if (!url.pathname.startsWith("/__wrnexus/dev-toolbar")) return null;
  if (options.mode !== "development") return new Response("Not found", { status: 404 });
  if (url.pathname === "/__wrnexus/dev-toolbar.js" && request.method === "GET")
    return new Response(DEV_TOOLBAR_RUNTIME, {
      headers: { "content-type": "text/javascript; charset=utf-8", "cache-control": "no-store" },
    });
  if (url.pathname === "/__wrnexus/dev-toolbar.css" && request.method === "GET")
    return new Response(DEV_TOOLBAR_CSS, {
      headers: { "content-type": "text/css; charset=utf-8", "cache-control": "no-store" },
    });
  if (url.pathname === "/__wrnexus/dev-toolbar/issues" && request.method === "GET")
    return json({
      issues: options.collector.getIssues(url.searchParams.get("pathname") ?? undefined),
    });
  if (url.pathname === "/__wrnexus/dev-toolbar/platform" && request.method === "GET") {
    const panels = typeof options.panels === "function" ? await options.panels() : options.panels;
    return json({ platform: options.platform ?? null, panels: panels ?? [] });
  }
  if (url.pathname === "/__wrnexus/dev-toolbar/open-editor" && request.method === "POST") {
    if (options.allowOpenEditor === false)
      return json({ error: "Open in editor is disabled." }, 403);
    const body = (await request.json().catch(() => null)) as {
      file?: string;
      line?: number;
      column?: number;
    } | null;
    if (!body?.file) return json({ error: "file is required" }, 400);
    try {
      openInEditor(
        { file: body.file, line: body.line, column: body.column },
        { root: options.root, editor: options.editor },
      );
      return json({ ok: true });
    } catch (error) {
      return json({ error: error instanceof Error ? error.message : String(error) }, 400);
    }
  }
  return new Response("Not found", { status: 404 });
}
