import { describe, expect, it } from "vitest";
import {
  GUARD_REGEX,
  PUBLIC_ACTION_ALLOWLIST,
  findUnguardedActions,
  findUnguardedActionsInRepo,
} from "../support/guard-scan";

/**
 * Statischer Default-Deny-Beweis für Server Actions (Querschnittsstandard 3,
 * Definition of Done #2): JEDE "use server"-Funktion ruft als erste Anweisung
 * einen Guard. Dieser Test ist OHNE Server/DB lauffähig und prüft das echte
 * Repository.
 */
describe("findUnguardedActions (pure)", () => {
  it("flaggt eine exportierte Action ohne Guard", () => {
    const src = `"use server";
export async function tut_was(x: unknown) {
  return doThing(x);
}`;
    expect(findUnguardedActions("x.ts", src)).toEqual([
      "x.ts: tut_was",
    ]);
  });

  it("akzeptiert eine Action, die mit requireWehrAdmin beginnt", () => {
    const src = `"use server";
export async function tut_was(x: unknown) {
  const s = await requireWehrAdmin();
  return doThing(x, s);
}`;
    expect(findUnguardedActions("x.ts", src)).toEqual([]);
  });

  it("akzeptiert requirePlatformAdmin / requireSession / requireRole / requireOwnBrigade", () => {
    for (const guard of [
      "requirePlatformAdmin",
      "requireSession",
      "requireRole",
      "requireOwnBrigade",
    ]) {
      const src = `"use server";
export async function f(x: unknown) {
  await ${guard}();
  return x;
}`;
      expect(findUnguardedActions("x.ts", src)).toEqual([]);
    }
  });

  it("ignoriert Dateien ohne \"use server\"-Direktive", () => {
    const src = `export async function f(x: unknown) { return x; }`;
    expect(findUnguardedActions("x.ts", src)).toEqual([]);
  });

  it("respektiert die Allowlist genuin öffentlicher Actions", () => {
    const src = `"use server";
export async function loginAction(x: unknown) { return x; }`;
    expect(
      findUnguardedActions(
        "src/app/(auth)/login/actions.ts",
        src,
        new Set(["src/app/(auth)/login/actions.ts:loginAction"]),
      ),
    ).toEqual([]);
  });

  it("hat die Login-Actions in der Default-Allowlist", () => {
    expect(PUBLIC_ACTION_ALLOWLIST.has("src/app/(auth)/login/actions.ts:loginAction")).toBe(true);
    expect(
      PUBLIC_ACTION_ALLOWLIST.has("src/app/(auth)/login/actions.ts:authentikLoginAction"),
    ).toBe(true);
  });

  it("GUARD_REGEX matcht alle fünf Guard-Namen", () => {
    expect(GUARD_REGEX.test("requireSession(")).toBe(true);
    expect(GUARD_REGEX.test("requirePlatformAdmin(")).toBe(true);
    expect(GUARD_REGEX.test("doSomething(")).toBe(false);
  });
});

describe("findUnguardedActionsInRepo (echtes Repo)", () => {
  it("findet KEINE ungeschützten Server Actions im echten src/", () => {
    const offenders = findUnguardedActionsInRepo();
    expect(
      offenders,
      `Server Actions ohne Guard:\n${offenders.join("\n")}`,
    ).toEqual([]);
  });
});
