import { auth } from "@haushaltsApp/auth";
import app from "../../index";

export interface TestContext {
  token: string;
  householdId: string;
  userId: string;
  email: string;
}

export async function createTestContext(suffix?: string): Promise<TestContext> {
  const unique = suffix ?? String(Date.now());
  const email = `test-${unique}@example.com`;
  const password = "TestPassword123!";
  const name = `Test User ${unique}`;

  // 1. Register user
  const signUpRes = await app.request("/api/auth/sign-up/email", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ email, password, name }),
  });
  if (!signUpRes.ok) throw new Error(`Sign-up failed: ${await signUpRes.text()}`);

  // 2. Sign in to get token
  const signInRes = await app.request("/api/auth/sign-in/email", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ email, password }),
  });
  if (!signInRes.ok) throw new Error(`Sign-in failed: ${await signInRes.text()}`);
  const signInBody = (await signInRes.json()) as { token: string; user: { id: string } };
  const token = signInBody.token;
  const userId = signInBody.user.id;

  // 3. Create organization (household) via Better Auth API
  const orgRes = await auth.api.createOrganization({
    body: {
      name: `Household ${unique}`,
      slug: `household-${unique}`,
      userId,
    },
  });
  const householdId = orgRes.id;

  // 4. Seed default categories
  await app.request("/api/households/setup", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${token}`,
      "x-household-id": householdId,
    },
  });

  return { token, householdId, userId, email };
}

export function authHeaders(token: string, householdId: string) {
  return {
    "Content-Type": "application/json",
    Authorization: `Bearer ${token}`,
    "x-household-id": householdId,
  };
}
