import { test, expect, handleElementDialogs } from "../fixtures/persistent-context";
import {
  goToRoom,
  sendMessage,
  waitForBotReply,
  assertNoDecryptionErrors,
} from "../fixtures/matrix-room";

test.describe("test-bot (robot)", () => {
  test.beforeEach(async ({ page }) => {
    await page.goto("/");
    await handleElementDialogs(page);
    await goToRoom(page, "Test Bot");
  });

  test("help lista comandos built-in y custom", async ({ page }) => {
    await sendMessage(page, "help");

    const reply = await waitForBotReply(page, {
      timeout: 10_000,
      sender: "Test Bot",
    });
    expect(reply).toBeTruthy();
    expect(reply.toLowerCase()).toContain("help");
    expect(reply.toLowerCase()).toContain("ping");
    expect(reply.toLowerCase()).toContain("echo");
    expect(reply.toLowerCase()).toContain("dice");
  });

  test("ping responde sin prefijo !", async ({ page }) => {
    await sendMessage(page, "ping");

    const reply = await waitForBotReply(page, {
      timeout: 10_000,
      sender: "Test Bot",
    });
    expect(reply).toBeTruthy();
  });

  test("!ping tambien funciona (retrocompatible)", async ({ page }) => {
    await sendMessage(page, "!ping");

    const reply = await waitForBotReply(page, {
      timeout: 10_000,
      sender: "Test Bot",
    });
    expect(reply).toBeTruthy();
  });

  test("echo repite el texto exacto", async ({ page }) => {
    await sendMessage(page, "echo hello world");

    const reply = await waitForBotReply(page, {
      timeout: 10_000,
      sender: "Test Bot",
    });
    expect(reply).toBe("hello world");
  });

  test("dice devuelve un numero entre 1 y 6", async ({ page }) => {
    await sendMessage(page, "dice");

    const reply = await waitForBotReply(page, {
      timeout: 10_000,
      sender: "Test Bot",
    });
    expect(reply).toBeTruthy();
    const num = parseInt(reply.trim(), 10);
    expect(num).toBeGreaterThanOrEqual(1);
    expect(num).toBeLessThanOrEqual(6);
  });

  test("comando desconocido muestra error", async ({ page }) => {
    await sendMessage(page, "unknowncommand");

    const reply = await waitForBotReply(page, {
      timeout: 10_000,
      sender: "Test Bot",
    });
    expect(reply).toBeTruthy();
    expect(reply.toLowerCase()).toMatch(/desconocido|unknown|no reconozco/);
  });

  test("no hay errores de E2EE en el timeline", async ({ page }) => {
    await assertNoDecryptionErrors(page);
  });
});
