import { afterAll, beforeAll, describe, expect, it } from "bun:test";
import { db, eq } from "@haushaltsApp/db";
import { account, categories, households as householdsTable, session, user } from "@haushaltsApp/db/schema";
import app from "../../index";
import { authHeaders, createTestContext, type TestContext } from "../helpers/test-context";

let ctx: TestContext;

beforeAll(async () => {
  ctx = await createTestContext(`hh-${Date.now()}`);
});

afterAll(async () => {
  const [u] = await db.select().from(user).where(eq(user.email, ctx.email));
  if (u) {
    await db.delete(categories).where(eq(categories.householdId, ctx.householdId));
    await db.delete(householdsTable).where(eq(householdsTable.id, ctx.householdId));
    await db.delete(session).where(eq(session.userId, u.id));
    await db.delete(account).where(eq(account.userId, u.id));
    await db.delete(user).where(eq(user.id, u.id));
  }
});

describe("Household Routes", () => {
  it("GET /api/households — returns list of households for user", async () => {
    const res = await app.request("/api/households", {
      headers: authHeaders(ctx.token, ctx.householdId),
    });
    expect(res.status).toBe(200);
    const body = (await res.json()) as { households: { id: string; name: string; role: string }[] };
    expect(Array.isArray(body.households)).toBe(true);
    expect(body.households.length).toBeGreaterThan(0);
    expect(body.households[0]?.id).toBe(ctx.householdId);
  });
});
