import { describe, it, expect } from "vitest";
import { matchesChannelSub, matchesAgentSub, type Sub } from "./subscriptions.js";

const ev = (over: Partial<{ channel: string; accountId: string }> = {}) => ({
  channel: "telegram",
  accountId: "default",
  chatId: "c",
  content: "x",
  isGroup: false,
  ...over,
});

describe("matchesChannelSub", () => {
  it("matches exact channel+account", () => {
    const subs: Sub[] = [{ kind: "channel", channel: "telegram", accountId: "default" }];
    expect(matchesChannelSub(subs, ev())).toBe(true);
  });

  it("matches channel when accountId is omitted in sub", () => {
    const subs: Sub[] = [{ kind: "channel", channel: "telegram" }];
    expect(matchesChannelSub(subs, ev({ accountId: "other" }))).toBe(true);
  });

  it("rejects mismatched channel", () => {
    const subs: Sub[] = [{ kind: "channel", channel: "whatsapp" }];
    expect(matchesChannelSub(subs, ev())).toBe(false);
  });

  it("rejects mismatched account when accountId is specified", () => {
    const subs: Sub[] = [{ kind: "channel", channel: "telegram", accountId: "default" }];
    expect(matchesChannelSub(subs, ev({ accountId: "other" }))).toBe(false);
  });

  it("catch-all matches everything", () => {
    const subs: Sub[] = [{ kind: "channel-catchall" }];
    expect(matchesChannelSub(subs, ev())).toBe(true);
    expect(matchesChannelSub(subs, ev({ channel: "discord" }))).toBe(true);
  });

  it("empty subs matches nothing", () => {
    expect(matchesChannelSub([], ev())).toBe(false);
  });
});

describe("matchesAgentSub", () => {
  it("matches agentId", () => {
    const subs: Sub[] = [{ kind: "agent", agentId: "panik" }];
    expect(matchesAgentSub(subs, "panik")).toBe(true);
  });

  it("rejects when agentId is undefined", () => {
    const subs: Sub[] = [{ kind: "agent", agentId: "panik" }];
    expect(matchesAgentSub(subs, undefined)).toBe(false);
  });
});
