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 0093: reporte diario al pulsar numero del dia en el calendario.
 * Verifica: endpoint responde, calendario abre modal con titulo "Reporte diario",
 * KPIs visibles, tabla de hechas presente.
 */
test.describe("daily report (issue 0093)", () => {
  test("endpoint /api/reports/daily devuelve estructura esperada", async ({ page }) => {
    await page.goto("/");
    await pw_kanban_login(page, { username: USER, password: PWD });
    const today = new Date().toISOString().slice(0, 10);
    const res = await page.request.get(`/api/reports/daily?date=${today}`);
    expect(res.status()).toBe(200);
    const data = await res.json();
    expect(data).toHaveProperty("kpis");
    expect(data).toHaveProperty("done_cards");
    expect(data).toHaveProperty("hourly_moves");
    expect(Array.isArray(data.hourly_moves)).toBe(true);
    expect(data.hourly_moves.length).toBe(24);
    expect(data).toHaveProperty("stale_cards");
    expect(data.stale_cards).toHaveProperty("d7");
    expect(data.stale_cards).toHaveProperty("d14");
    expect(data.stale_cards).toHaveProperty("d30");
  });

  test("click en numero del dia del calendario abre modal del reporte", async ({ page }) => {
    await page.goto("/");
    await pw_kanban_login(page, { username: USER, password: PWD });

    // Switch to Calendario tab.
    await page.getByRole("tab", { name: /Calendario/i }).click();

    // Wait until the calendar cells render.
    await page.waitForSelector('[data-test^="calendar-day-"]', { timeout: 5000 });

    // Use yesterday — the seeded DB has activity there.
    const yesterday = new Date(Date.now() - 24 * 3600 * 1000).toISOString().slice(0, 10);
    const cellBtn = page.locator(`[data-test="calendar-day-${yesterday}"]`);
    if ((await cellBtn.count()) === 0) {
      // Fallback: click any visible day.
      await page.locator('[data-test^="calendar-day-"]').first().dispatchEvent("click");
    } else {
      await cellBtn.dispatchEvent("click");
    }

    // Modal opens.
    const modal = page.locator('[role="dialog"]').filter({ hasText: /Reporte diario/i });
    await expect(modal).toBeVisible({ timeout: 5000 });
    await expect(modal.getByText("Hechas", { exact: false }).first()).toBeVisible();
    await expect(modal.getByText("Movimientos", { exact: false }).first()).toBeVisible();
  });
});
