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

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

test.beforeEach(async ({ context, page }) => {
  await context.addCookies([
    { name: "ledgerone_auth", value: "1", domain: "localhost", path: "/" },
  ]);
  await page.route("**/api/auth/me", async (route) => {
    await route.fulfill({
      contentType: "application/json",
      body: JSON.stringify(apiOk({ user: { id: "user_1", email: "test@example.com", name: "Test User" } })),
    });
  });
  await page.route("**/api/billing/subscription", async (route) => {
    await route.fulfill({
      contentType: "application/json",
      body: JSON.stringify(apiOk({ plan: "pro", status: "active" })),
    });
  });
});

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/view/accounts**", async (route) => {
    await route.fulfill({
      contentType: "application/json",
      body: JSON.stringify(apiOk({ accounts: [{ viewRef: "acct_1" }, { viewRef: "acct_2" }], total: 2 }))
    });
  });
  await page.route("**/api/view/transactions**", async (route) => {
    await route.fulfill({
      contentType: "application/json",
      body: JSON.stringify(apiOk({
        transactions: [
          { viewRef: "tx_1", date: "2025-09-10", description: "Acme Corp", category: "Office", amount: "-25.00" }
        ],
        total: 1
      }))
    });
  });

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