import { describe, expect, test } from "bun:test";
import { resolveChannel, ResolveError, type BotRow } from "./resolve.js";

const FIXTURE_ROWS: BotRow[] = [
  {
    id: "EtKy9VN1E6",
    project_name: "overdeck",
    bot_name: "OverdeckBot",
    telegram_token: "fake-overdeck-token",
    allowed_chat_ids: "-5587004522",
  },
  {
    id: "4laMbKGL04",
    project_name: "Hetzi",
    bot_name: "HetziBot",
    telegram_token: "fake-hetzi-token",
    allowed_chat_ids: "-5289977597,-5289977598",
  },
  {
    id: "NOTOKEN01",
    project_name: "notoken",
    bot_name: "NoTokenBot",
    telegram_token: "",
    allowed_chat_ids: "-1000000001",
  },
  {
    id: "NOCHAT001",
    project_name: "nochat",
    bot_name: "NoChatBot",
    telegram_token: "fake-nochat-token",
    allowed_chat_ids: "",
  },
  {
    id: "DUP0001",
    project_name: "duplicate",
    bot_name: "DupA",
    telegram_token: "fake-dup-a",
    allowed_chat_ids: "-1",
  },
  {
    id: "DUP0002",
    project_name: "duplicate",
    bot_name: "DupB",
    telegram_token: "fake-dup-b",
    allowed_chat_ids: "-2",
  },
];

describe("resolveChannel", () => {
  test("resolves by project_name, case-insensitive", () => {
    const target = resolveChannel(FIXTURE_ROWS, "Overdeck");
    expect(target).toEqual({
      botId: "EtKy9VN1E6",
      botName: "OverdeckBot",
      token: "fake-overdeck-token",
      chatId: "-5587004522",
    });
  });

  test("resolves by bot_name, case-insensitive", () => {
    const target = resolveChannel(FIXTURE_ROWS, "hetzibot");
    expect(target.botId).toBe("4laMbKGL04");
  });

  test("takes the first chat id when a bot has several", () => {
    const target = resolveChannel(FIXTURE_ROWS, "Hetzi");
    expect(target.chatId).toBe("-5289977597");
  });

  test("unknown channel fails closed", () => {
    expect(() => resolveChannel(FIXTURE_ROWS, "no-such-channel")).toThrow(ResolveError);
    try {
      resolveChannel(FIXTURE_ROWS, "no-such-channel");
      throw new Error("expected resolveChannel to throw");
    } catch (error) {
      expect(String((error as Error).message)).toContain('unknown channel "no-such-channel"');
    }
  });

  test("ambiguous channel (two bots share a name) fails closed", () => {
    expect(() => resolveChannel(FIXTURE_ROWS, "duplicate")).toThrow(/ambiguous channel/);
  });

  test("missing token fails closed", () => {
    expect(() => resolveChannel(FIXTURE_ROWS, "notoken")).toThrow(/missing telegram token/);
  });

  test("missing chat id fails closed", () => {
    expect(() => resolveChannel(FIXTURE_ROWS, "nochat")).toThrow(/missing chat id/);
  });

  test("empty channel name fails closed", () => {
    expect(() => resolveChannel(FIXTURE_ROWS, "   ")).toThrow(/channel name is empty/);
  });
});
