import { test, expect } from "@playwright/test";
import { pw_kanban_login } from "../../../../frontend/functions/browser/pw_kanban_login";

const USER = process.env.KANBAN_USER || "e2e_user";
const PWD = process.env.KANBAN_PWD || "e2e_test_pw_2026";

/**
 * Issue 0094: bocadillo del agente + settings de prompt + PDF.
 * No invocamos claude binario; testeamos endpoints settings y la UI estatica.
 */
test.describe("daily summary + pdf (issue 0094)", () => {
  test("settings prompt CRUD roundtrip", async ({ page }) => {
    await page.goto("/");
    await pw_kanban_login(page, { username: USER, password: PWD });

    // Lectura inicial: existe seed.
    const initial = await page.request.get("/api/settings/daily_report_prompt").then((r) => r.json());
    expect(initial.value).toContain("MAXIMO");

    // Cambio.
    const newVal = "test prompt " + Date.now();
    const put = await page.request.put("/api/settings/daily_report_prompt", { data: { value: newVal } });
    expect([200, 204]).toContain(put.status());

    // Verifica.
    const after = await page.request.get("/api/settings/daily_report_prompt").then((r) => r.json());
    expect(after.value).toBe(newVal);

    // Restaurar.
    await page.request.put("/api/settings/daily_report_prompt", { data: { value: initial.value } });
  });

  test("daily summary GET vacio inicialmente, persiste si guardas manualmente", async ({ page }) => {
    await page.goto("/");
    await pw_kanban_login(page, { username: USER, password: PWD });
    const today = new Date().toISOString().slice(0, 10);
    const before = await page.request.get(`/api/reports/daily/summary?date=${today}`).then((r) => r.json());
    // Either exists=false OR exists=true with a string summary. Both valid.
    expect(typeof before.exists).toBe("boolean");
    expect(typeof before.summary === "string").toBe(true);
  });

  test("UI: bocadillo + boton PDF + boton settings visibles en modal", async ({ page }) => {
    await page.goto("/");
    await pw_kanban_login(page, { username: USER, password: PWD });
    await page.getByRole("tab", { name: /Calendario/i }).click();
    await page.waitForSelector('[data-test^="calendar-day-"]', { timeout: 5000 });
    await page.locator('[data-test^="calendar-day-"]').first().dispatchEvent("click");

    const modal = page.locator('[role="dialog"]').filter({ hasText: /Reporte diario/i });
    await expect(modal).toBeVisible();
    await expect(modal.locator('[data-test="daily-report-pdf"]')).toBeVisible();
    await expect(modal.getByRole("button", { name: /Configurar prompt/i })).toBeVisible();
    await expect(modal.getByRole("button", { name: /Regenerar|Generar/i }).first()).toBeVisible();
  });
});
