import { describe, it, expect, beforeEach, afterEach } from "vitest";
import fs from "fs";
import os from "os";
import path from "path";
import { registerGroup, updateGroupSettings } from "../src/modules/groups.js";

let tmpDir: string;

function readMessages(tmpDir: string) {
  const messagesDir = path.join(tmpDir, "messages");
  if (!fs.existsSync(messagesDir)) return [];
  return fs.readdirSync(messagesDir)
    .filter((f) => f.endsWith(".json"))
    .map((f) => JSON.parse(fs.readFileSync(path.join(messagesDir, f), "utf8")));
}

beforeEach(() => {
  tmpDir = path.join(os.tmpdir(), "treehouse-test-" + Math.random().toString(36).slice(2));
  fs.mkdirSync(tmpDir, { recursive: true });
  process.env.TENANT_ID = "test-tenant";
  process.env.NANOCLAW_GROUP_FOLDER = "test/group";
});

afterEach(() => {
  fs.rmSync(tmpDir, { recursive: true, force: true });
  delete process.env.TENANT_ID;
  delete process.env.NANOCLAW_GROUP_FOLDER;
});

describe("registerGroup", () => {
  it("writes register_group IPC message", async () => {
    await registerGroup(
      { jid: "1234@g.us", name: "My Group", folder: "whatsapp_my-group", trigger: "@Bot" },
      tmpDir
    );
    const msgs = readMessages(tmpDir);
    expect(msgs).toHaveLength(1);
    expect(msgs[0]).toMatchObject({
      type: "register_group",
      jid: "1234@g.us",
      name: "My Group",
      folder: "whatsapp_my-group",
      trigger: "@Bot",
      groupFolder: "test/group",
    });
  });
});

describe("updateGroupSettings", () => {
  it("writes update_group_settings IPC message", async () => {
    await updateGroupSettings({ requiresTrigger: true }, tmpDir);
    const msgs = readMessages(tmpDir);
    expect(msgs[0]).toMatchObject({
      type: "update_group_settings",
      requiresTrigger: true,
      groupFolder: "test/group",
    });
  });

  it("writes update_group_settings with false", async () => {
    await updateGroupSettings({ requiresTrigger: false }, tmpDir);
    const msgs = readMessages(tmpDir);
    expect(msgs[0]).toMatchObject({ type: "update_group_settings", requiresTrigger: false });
  });
});
