import { beforeEach, describe, expect, it } from "vitest";
import { createPluginRecord } from "../plugins/status.test-helpers.js";
import {
  buildPluginDiagnosticsReport,
  buildPluginSnapshotReport,
  resetPluginsCliTestState,
  runPluginsCommand,
  runtimeLogs,
} from "./plugins-cli-test-helpers.js";

describe("plugins cli list", () => {
  beforeEach(() => {
    resetPluginsCliTestState();
  });

  it("includes imported state in JSON output", async () => {
    buildPluginSnapshotReport.mockReturnValue({
      workspaceDir: "/workspace",
      plugins: [
        createPluginRecord({
          id: "demo",
          imported: true,
          activated: true,
          explicitlyEnabled: true,
        }),
      ],
      diagnostics: [],
    });

    await runPluginsCommand(["plugins", "list", "--json"]);

    expect(buildPluginSnapshotReport).toHaveBeenCalledWith();

    expect(JSON.parse(runtimeLogs[0] ?? "null")).toEqual({
      workspaceDir: "/workspace",
      plugins: [
        expect.objectContaining({
          id: "demo",
          imported: true,
          activated: true,
          explicitlyEnabled: true,
        }),
      ],
      diagnostics: [],
    });
  });

  it("shows imported state in verbose output", async () => {
    buildPluginSnapshotReport.mockReturnValue({
      plugins: [
        createPluginRecord({
          id: "demo",
          name: "Demo Plugin",
          imported: false,
          activated: true,
          explicitlyEnabled: false,
        }),
      ],
      diagnostics: [],
    });

    await runPluginsCommand(["plugins", "list", "--verbose"]);

    expect(buildPluginSnapshotReport).toHaveBeenCalledWith();

    const output = runtimeLogs.join("\n");
    expect(output).toContain("activated: yes");
    expect(output).toContain("imported: no");
    expect(output).toContain("explicitly enabled: no");
  });

  it("sanitizes activation reasons in verbose output", async () => {
    buildPluginSnapshotReport.mockReturnValue({
      plugins: [
        createPluginRecord({
          id: "demo",
          name: "Demo Plugin",
          activated: true,
          activationSource: "auto",
          activationReason: "\u001B[31mconfigured\nnext\tstep",
        }),
      ],
      diagnostics: [],
    });

    await runPluginsCommand(["plugins", "list", "--verbose"]);

    const output = runtimeLogs.join("\n");
    expect(output).toContain("activation reason: configured\\nnext\\tstep");
    expect(output).not.toContain("\u001B[31m");
    expect(output.match(/activation reason:/g)).toHaveLength(1);
  });

  it("keeps doctor on a module-loading snapshot", async () => {
    buildPluginDiagnosticsReport.mockReturnValue({
      plugins: [],
      diagnostics: [],
    });

    await runPluginsCommand(["plugins", "doctor"]);

    expect(buildPluginDiagnosticsReport).toHaveBeenCalledWith();
    expect(runtimeLogs).toContain("No plugin issues detected.");
  });
});
