import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { describe, it, expect, beforeEach, afterEach } from "vitest";
import { runScreenPageSyncCheck } from "./screen-pages";

describe("runScreenPageSyncCheck", () => {
  let tmpDir: string;

  beforeEach(() => {
    tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "sync-check-screen-"));
  });

  afterEach(() => {
    fs.rmSync(tmpDir, { recursive: true, force: true });
  });

  function setupScreenFixture(screenDocs: string[], pageObjects: { dir: string; name: string }[]) {
    const screenDir = path.join(tmpDir, "my-app", "docs", "screen");
    fs.mkdirSync(screenDir, { recursive: true });
    for (const name of screenDocs) {
      fs.writeFileSync(path.join(screenDir, `${name}.md`), `# ${name}\n`);
    }
    for (const { dir, name } of pageObjects) {
      const pageDir = path.join(tmpDir, "my-app", "frontend", "e2e", "pages", dir);
      fs.mkdirSync(pageDir, { recursive: true });
      fs.writeFileSync(path.join(pageDir, `${name}.ts`), `export class ${name} {}\n`);
    }
  }

  it("returns no errors when screen docs and page objects match", async () => {
    setupScreenFixture(
      ["login", "item-list"],
      [
        { dir: "auth", name: "login" },
        { dir: "item", name: "item-list" },
      ],
    );

    const { errors } = await runScreenPageSyncCheck("my-app", tmpDir);
    expect(errors).toHaveLength(0);
  });

  it("reports missing-page-object when screen doc has no page object", async () => {
    setupScreenFixture(["login", "item-list"], [{ dir: "auth", name: "login" }]);

    const { errors } = await runScreenPageSyncCheck("my-app", tmpDir);
    expect(errors).toContainEqual(
      expect.objectContaining({
        type: "missing-page-object",
        category: "screen",
        expectedBasename: "item-list.ts",
      }),
    );
  });

  it("allows page objects without screen docs", async () => {
    setupScreenFixture(
      ["login"],
      [
        { dir: "auth", name: "login" },
        { dir: "item", name: "item-list" },
      ],
    );

    const { errors } = await runScreenPageSyncCheck("my-app", tmpDir);
    expect(errors).toHaveLength(0);
  });

  it("returns no errors when neither screen docs nor page objects exist", async () => {
    fs.mkdirSync(path.join(tmpDir, "my-app"), { recursive: true });
    const { errors } = await runScreenPageSyncCheck("my-app", tmpDir);
    expect(errors).toHaveLength(0);
  });
});
