import { test, expect } from "@playwright/test";

const apiOk = (data: unknown) => ({
  data,
  meta: { timestamp: new Date().toISOString(), version: "v1" },
  error: null
});

test.beforeEach(async ({ page }) => {
  await page.addInitScript(() => {
    localStorage.setItem("ledgerone_user_id", "test_user");
  });
});

test("dashboard renders summary, cashflow, and merchants", async ({ page }) => {
  await page.route("**/api/transactions/summary**", async (route) => {
    await route.fulfill({
      contentType: "application/json",
      body: JSON.stringify(apiOk({ total: "120.00", count: 4, income: "300.00", expense: "180.00", net: "120.00" }))
    });
  });
  await page.route("**/api/transactions/cashflow**", async (route) => {
    await route.fulfill({
      contentType: "application/json",
      body: JSON.stringify(
        apiOk([
          { month: "2025-09", income: "1000.00", expense: "800.00", net: "200.00" },
          { month: "2025-10", income: "900.00", expense: "950.00", net: "-50.00" }
        ])
      )
    });
  });
  await page.route("**/api/transactions/merchants**", async (route) => {
    await route.fulfill({
      contentType: "application/json",
      body: JSON.stringify(
        apiOk([
          { merchant: "Acme Corp", total: "250.00", count: 2 },
          { merchant: "City Market", total: "120.00", count: 1 }
        ])
      )
    });
  });
  await page.route("**/api/accounts**", async (route) => {
    await route.fulfill({
      contentType: "application/json",
      body: JSON.stringify(apiOk([{ id: "acct_1" }, { id: "acct_2" }]))
    });
  });

  await page.goto("/app");
  await expect(page.getByText("Income (30d)")).toBeVisible();
  await expect(page.getByText("Top Merchants")).toBeVisible();
  await expect(page.getByText("Acme Corp")).toBeVisible();
  await expect(page.getByText("2025-09")).toBeVisible();
});
