import { mkdirSync, writeFileSync, existsSync, unlinkSync, readdirSync } from "node:fs";
import { paths } from "../lifecycle/paths";

const SESSION_ID_RE = /^[A-Za-z0-9_-]{1,128}$/;

function validateSessionId(raw: string | null): string | null {
  if (!raw || raw.includes("\0") || raw.includes("/") || raw.includes("\\") || raw.includes("..")) {
    return null;
  }
  return SESSION_ID_RE.test(raw) ? raw : null;
}

/**
 * Handles fewtok kill-switch control routes: /_ft/on, /_ft/off, /_ft/status.
 * All routes are localhost-only (proxy binds 127.0.0.1).
 */
export function handleControl(req: Request): Response {
  const url = new URL(req.url);
  const method = req.method.toUpperCase();
  const path = url.pathname;

  if (path === "/_ft/off" && method === "POST") {
    const session = validateSessionId(url.searchParams.get("session"));
    if (!session) {
      return Response.json({ ok: false, error: "invalid-session" }, { status: 400 });
    }
    mkdirSync(paths.bypassDir(), { recursive: true, mode: 0o700 });
    writeFileSync(paths.bypassFile(session), "", { mode: 0o600 });
    return Response.json({ ok: true, bypassed: true });
  }

  if (path === "/_ft/on" && method === "POST") {
    const session = validateSessionId(url.searchParams.get("session"));
    if (!session) {
      return Response.json({ ok: false, error: "invalid-session" }, { status: 400 });
    }
    if (existsSync(paths.bypassFile(session))) {
      unlinkSync(paths.bypassFile(session));
    }
    return Response.json({ ok: true, bypassed: false });
  }

  if (path === "/_ft/status" && method === "GET") {
    let rawNames: string[] = [];
    try {
      rawNames = readdirSync(paths.bypassDir());
    } catch {
      // bypass dir doesn't exist = no bypassed sessions
    }
    const sessions = rawNames.filter((name) => validateSessionId(name) !== null);
    return Response.json({ ok: true, count: sessions.length, sessions });
  }

  return Response.json({ ok: false, error: "not-found" }, { status: 404 });
}
