import { describe, expect, it } from "vitest";
import {
  extractExportedFunctionBody,
  extractExportedFunctions,
  extractExportedMethodBodies,
  readBalancedBlock,
} from "./backend-discovery.mjs";

describe("coverage backend discovery helpers", () => {
  it("extracts exported HTTP method bodies without being confused by braces in strings", () => {
    const content = `
      export async function GET() {
        const template = "{not a block}";
        return template;
      }

      export async function POST() {
        return { ok: true };
      }
    `;

    expect(extractExportedMethodBodies(content, ["GET", "POST"])).toEqual([
      ["GET", expect.stringContaining('"{not a block}"')],
      ["POST", expect.stringContaining("{ ok: true }")],
    ]);
  });

  it("extracts named exported functions and their bodies", () => {
    const content = `
      export async function saveSettings() {
        return updateSettings();
      }

      export function listSettings() {
        return [];
      }
    `;

    expect(extractExportedFunctions(content)).toEqual([
      { name: "saveSettings", body: expect.stringContaining("updateSettings") },
      { name: "listSettings", body: expect.stringContaining("return [];") },
    ]);
    expect(extractExportedFunctionBody(content, "saveSettings")).toContain("updateSettings");
  });

  it("reads a balanced block from a brace offset", () => {
    const content = `before { const tpl = \`{nested}\`; return tpl; } after`;
    const startIndex = content.indexOf("{");

    expect(readBalancedBlock(content, startIndex)).toBe("{ const tpl = `{nested}`; return tpl; }");
  });
});
