import "./setup-env.js";
import { describe, expect, it, beforeAll, afterAll } from "vitest";
import { eq, inArray } from "drizzle-orm";
import { buildServer } from "../src/server.js";
import { loadConfig } from "../src/config.js";
import { createDatabase, closeDatabase, schema } from "@app/database";

describe("admin household trust score", () => {
  const testDb = createDatabase(process.env.TEST_DATABASE_URL!);
  const config = loadConfig();
  let app: Awaited<ReturnType<typeof buildServer>>;
  let adminToken: string;
  let householdId: string;
  const adminEmail = "admin-trust@example.invalid";

  async function cleanup() {
    const existing = await testDb.db
      .select({ id: schema.users.id })
      .from(schema.users)
      .where(inArray(schema.users.email, [adminEmail]));
    for (const u of existing) {
      await testDb.db.delete(schema.inventoryTransactions).where(eq(schema.inventoryTransactions.actorUserId, u.id));
      const owned = await testDb.db
        .select({ id: schema.households.id })
        .from(schema.households)
        .innerJoin(schema.householdMembers, eq(schema.householdMembers.householdId, schema.households.id))
        .where(eq(schema.householdMembers.userId, u.id));
      for (const h of owned) {
        await testDb.db.delete(schema.inventoryItems).where(eq(schema.inventoryItems.householdId, h.id));
        await testDb.db.delete(schema.storageLocations).where(eq(schema.storageLocations.householdId, h.id));
        await testDb.db.delete(schema.households).where(eq(schema.households.id, h.id));
      }
      await testDb.db.delete(schema.householdMembers).where(eq(schema.householdMembers.userId, u.id));
      await testDb.db.delete(schema.userPreferences).where(eq(schema.userPreferences.userId, u.id));
      await testDb.db.delete(schema.users).where(eq(schema.users.id, u.id));
    }
  }

  beforeAll(async () => {
    await cleanup();
    app = await buildServer(config);
    await app.ready();

    const res = await app.inject({
      method: "POST",
      url: "/v1/auth/register",
      payload: { email: adminEmail, password: "Password123!", displayName: "Admin Trust" },
    });
    const body = JSON.parse(res.body) as { accessToken: string };
    adminToken = body.accessToken;
    const userId = (JSON.parse(atob(adminToken.split(".")[1]!)) as { sub: string }).sub;

    await testDb.db.update(schema.users).set({ role: "admin" }).where(eq(schema.users.id, userId));

    const quick = await app.inject({
      method: "POST",
      url: "/v1/onboarding/quick-start",
      headers: { authorization: `Bearer ${adminToken}` },
      payload: { goals: ["cook_more"], precisionMode: "simple" },
    });
    householdId = (JSON.parse(quick.body) as { householdId: string }).householdId;
  });

  afterAll(async () => {
    await cleanup();
    await closeDatabase();
    await app.close();
  });

  it("returns numeric score and status for admin", async () => {
    const res = await app.inject({
      method: "GET",
      url: `/admin/v1/households/${householdId}/trust`,
      headers: { authorization: `Bearer ${adminToken}` },
    });
    expect(res.statusCode).toBe(200);
    const body = JSON.parse(res.body) as { householdId: string; score: number; status: string; itemCount: number };
    expect(body.householdId).toBe(householdId);
    expect(typeof body.score).toBe("number");
    expect(["up_to_date", "needs_check", "uncertain"]).toContain(body.status);
    expect(body.itemCount).toBe(0);
  });
});
