import { afterAll, describe, expect, it } from "bun:test";
import { db, eq } from "@haushaltsApp/db";
import { account, session, user } from "@haushaltsApp/db/schema";
import app from "../../index";

const TEST_EMAIL = `test-${Date.now()}@example.com`;
const TEST_PASSWORD = "TestPassword123!";
const TEST_NAME = "Test User";

describe("Auth Routes", () => {
  afterAll(async () => {
    // Clean up test user and related records
    const [testUser] = await db
      .select()
      .from(user)
      .where(eq(user.email, TEST_EMAIL));
    if (testUser) {
      await db.delete(session).where(eq(session.userId, testUser.id));
      await db.delete(account).where(eq(account.userId, testUser.id));
      await db.delete(user).where(eq(user.id, testUser.id));
    }
  });

  it("POST /api/auth/sign-up/email — creates user", async () => {
    const res = await app.request("/api/auth/sign-up/email", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        email: TEST_EMAIL,
        password: TEST_PASSWORD,
        name: TEST_NAME,
      }),
    });
    expect(res.status).toBe(200);
    const body = (await res.json()) as { user: { email: string } };
    expect(body.user.email).toBe(TEST_EMAIL);
  });

  it("POST /api/auth/sign-in/email — returns session", async () => {
    const res = await app.request("/api/auth/sign-in/email", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        email: TEST_EMAIL,
        password: TEST_PASSWORD,
      }),
    });
    expect(res.status).toBe(200);
    const body = (await res.json()) as { token?: string; user?: { email: string } };
    // Better Auth sign-in returns { token, user } (session stored server-side via cookie)
    expect(body.token).toBeDefined();
    expect(body.user?.email).toBe(TEST_EMAIL);
  });
});
