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

const userEmail = "what-to-eat-repro@example.invalid";
const viewTestEmail = "view-test@example.invalid";

/**
 * Regression test: what-to-eat must work for a brand-new user who has not
 * created a household yet (empty pantry, single-person context).
 */
describe("what-to-eat without household", () => {
  const testDb = createDatabase(process.env.TEST_DATABASE_URL!);
  const config = loadConfig();
  let app: Awaited<ReturnType<typeof buildServer>>;
  let accessToken: string;

  async function cleanup() {
    const emails = [
      userEmail,
      "goals-multi@example.invalid",
      "auto-household@example.invalid",
      "personalization-gate@example.invalid",
      viewTestEmail,
    ];
    const existing = await testDb.db
      .select({ id: schema.users.id })
      .from(schema.users)
      .where(inArray(schema.users.email, emails));
    for (const u of existing) {
      await testDb.db
        .delete(schema.householdMembers)
        .where(eq(schema.householdMembers.userId, u.id));
      const ownedHouseholds = await testDb.db
        .select({ id: schema.households.id })
        .from(schema.households)
        .innerJoin(
          schema.householdMembers,
          eq(schema.householdMembers.householdId, schema.households.id),
        )
        .where(
          and(eq(schema.householdMembers.userId, u.id), eq(schema.householdMembers.role, "owner")),
        );
      for (const h of ownedHouseholds) {
        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.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: userEmail, password: "Password123!", displayName: "Repro" },
    });
    const body = JSON.parse(res.body) as { accessToken: string };
    accessToken = body.accessToken;

    await testDb.db
      .insert(schema.userPreferences)
      .values({
        userId: (JSON.parse(atob(accessToken.split(".")[1]!)) as { sub: string }).sub,
        primaryGoal: "cook_more",
      })
      .onConflictDoNothing();
  });

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

  it("returns recommendations for a new user without a household and a craving set", async () => {
    const res = await app.inject({
      method: "GET",
      url: "/v1/recommendations/what-to-eat?limit=5&craving=asiatiskt",
      headers: { authorization: `Bearer ${accessToken}` },
    });

    expect(res.statusCode).toBe(200);
    const body = JSON.parse(res.body) as {
      recommendations: unknown[];
      mealBoxSuggestions: unknown[];
      context: { persons: number; craving: { cuisine: string } | null };
    };
    expect(body.recommendations).toBeDefined();
    expect(body.mealBoxSuggestions).toBeDefined();
    expect(body.context.persons).toBe(1);
    expect(body.context.craving).not.toBeNull();
    expect(body.context.craving?.cuisine).toBe("thai");
  });

  it("quick-start stores goals array and sets primaryGoal to the first goal", async () => {
    const registerRes = await app.inject({
      method: "POST",
      url: "/v1/auth/register",
      payload: {
        email: "goals-multi@example.invalid",
        password: "Password123!",
        displayName: "Goals",
      },
    });
    const { accessToken: token } = JSON.parse(registerRes.body) as { accessToken: string };
    const userId = (JSON.parse(atob(token.split(".")[1]!)) as { sub: string }).sub;

    const quickRes = await app.inject({
      method: "POST",
      url: "/v1/onboarding/quick-start",
      headers: { authorization: `Bearer ${token}` },
      payload: { goals: ["cook_more", "less_waste"], precisionMode: "simple" },
    });
    expect(quickRes.statusCode).toBe(200);

    const [prefs] = await testDb.db
      .select()
      .from(schema.userPreferences)
      .where(eq(schema.userPreferences.userId, userId))
      .limit(1);

    expect(prefs?.goals).toEqual(["cook_more", "less_waste"]);
    expect(prefs?.primaryGoal).toBe("cook_more");
  });

  it("personalization is gated by consent: no provenance without granted consent", async () => {
    const registerRes = await app.inject({
      method: "POST",
      url: "/v1/auth/register",
      payload: {
        email: "personalization-gate@example.invalid",
        password: "Password123!",
        displayName: "Gate",
      },
    });
    const { accessToken: token } = JSON.parse(registerRes.body) as { accessToken: string };
    const userId = (JSON.parse(atob(token.split(".")[1]!)) as { sub: string }).sub;

    await app.inject({
      method: "POST",
      url: "/v1/onboarding/quick-start",
      headers: { authorization: `Bearer ${token}` },
      payload: { goals: ["cook_more"], persons: 2, precisionMode: "simple" },
    });

    // Without personalization consent: no personal signals read, no provenance.
    const withoutConsent = await app.inject({
      method: "GET",
      url: "/v1/recommendations/what-to-eat?limit=5",
      headers: { authorization: `Bearer ${token}` },
    });
    expect(withoutConsent.statusCode).toBe(200);
    const bodyWithout = JSON.parse(withoutConsent.body) as {
      recommendations: Array<{ provenance?: unknown[]; whySv: string }>;
    };
    expect(bodyWithout.recommendations.length).toBeGreaterThan(0);
    for (const r of bodyWithout.recommendations) {
      expect(r.provenance ?? []).toHaveLength(0);
      expect(r.whySv).not.toContain("berättat");
    }

    // Grant personalization consent.
    await testDb.db
      .insert(schema.userConsents)
      .values({ userId, kind: "personalization", status: "granted" })
      .onConflictDoUpdate({
        target: [schema.userConsents.userId, schema.userConsents.kind],
        set: { status: "granted" },
      });

    const withConsent = await app.inject({
      method: "GET",
      url: "/v1/recommendations/what-to-eat?limit=5",
      headers: { authorization: `Bearer ${token}` },
    });
    expect(withConsent.statusCode).toBe(200);
    const bodyWith = JSON.parse(withConsent.body) as {
      recommendations: Array<{ recipeId: string; provenance?: unknown[]; score: number }>;
    };
    expect(bodyWith.recommendations.length).toBeGreaterThan(0);
    // Consent alone does not guarantee provenance; it just enables the path.
    // We verify determinism: same call twice = same order.
    const second = await app.inject({
      method: "GET",
      url: "/v1/recommendations/what-to-eat?limit=5",
      headers: { authorization: `Bearer ${token}` },
    });
    const bodySecond = JSON.parse(second.body) as {
      recommendations: Array<{ recipeId: string; score: number }>;
    };
    expect(bodyWith.recommendations.map((r) => r.recipeId)).toEqual(
      bodySecond.recommendations.map((r) => r.recipeId),
    );
  });

  it("quick-start auto-creates a household with default storage locations", async () => {
    const registerRes = await app.inject({
      method: "POST",
      url: "/v1/auth/register",
      payload: {
        email: "auto-household@example.invalid",
        password: "Password123!",
        displayName: "Auto",
      },
    });
    const { accessToken: token } = JSON.parse(registerRes.body) as { accessToken: string };
    const userId = (JSON.parse(atob(token.split(".")[1]!)) as { sub: string }).sub;

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

    const [household] = await testDb.db
      .select()
      .from(schema.households)
      .where(eq(schema.households.id, householdId))
      .limit(1);
    expect(household).toBeTruthy();
    expect(household!.size).toBe(2);

    const locations = await testDb.db
      .select()
      .from(schema.storageLocations)
      .where(eq(schema.storageLocations.householdId, householdId));
    expect(locations.map((l) => l.type).sort()).toEqual(["freezer", "fridge", "pantry"]);
  });
});

describe("S4 recommendation views", () => {
  const testDb = createDatabase(process.env.TEST_DATABASE_URL!);
  const config = loadConfig();
  let app: Awaited<ReturnType<typeof buildServer>>;
  let accessToken: string;
  let userId: string;

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

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

    await app.inject({
      method: "POST",
      url: "/v1/onboarding/quick-start",
      headers: { authorization: `Bearer ${accessToken}` },
      payload: { goals: ["cook_more"], persons: 2, precisionMode: "simple" },
    });
  });

  afterAll(async () => {
    await app.close();
    await testDb.pool.end();
  });

  it("rejects unsupported view values", async () => {
    const res = await app.inject({
      method: "GET",
      url: "/v1/recommendations/what-to-eat?view=spicy&limit=1",
      headers: { authorization: `Bearer ${accessToken}` },
    });
    expect(res.statusCode).toBe(400);
  });

  it("returns requested view when personalization consent is granted", async () => {
    await testDb.db
      .insert(schema.userConsents)
      .values({ userId, kind: "personalization", status: "granted" })
      .onConflictDoUpdate({
        target: [schema.userConsents.userId, schema.userConsents.kind],
        set: { status: "granted" },
      });

    for (const view of ["taste", "health", "pantry"] as const) {
      const res = await app.inject({
        method: "GET",
        url: `/v1/recommendations/what-to-eat?view=${view}&limit=1`,
        headers: { authorization: `Bearer ${accessToken}` },
      });
      expect(res.statusCode).toBe(200);
      const body = JSON.parse(res.body) as {
        context: { view: string };
        recommendations: unknown[];
      };
      expect(body.context.view).toBe(view);
      expect(body.recommendations.length).toBeGreaterThan(0);
    }
  });

  it("honoreras vy och nollade personliga axlar utan samtycke", async () => {
    // Revoke consent.
    await testDb.db
      .insert(schema.userConsents)
      .values({ userId, kind: "personalization", status: "revoked" })
      .onConflictDoUpdate({
        target: [schema.userConsents.userId, schema.userConsents.kind],
        set: { status: "revoked" },
      });

    const defaultRes = await app.inject({
      method: "GET",
      url: "/v1/recommendations/what-to-eat?limit=5",
      headers: { authorization: `Bearer ${accessToken}` },
    });
    const pantryRes = await app.inject({
      method: "GET",
      url: "/v1/recommendations/what-to-eat?view=pantry&limit=5",
      headers: { authorization: `Bearer ${accessToken}` },
    });
    const healthRes = await app.inject({
      method: "GET",
      url: "/v1/recommendations/what-to-eat?view=health&limit=5",
      headers: { authorization: `Bearer ${accessToken}` },
    });
    const tasteRes = await app.inject({
      method: "GET",
      url: "/v1/recommendations/what-to-eat?view=taste&limit=5",
      headers: { authorization: `Bearer ${accessToken}` },
    });

    expect(defaultRes.statusCode).toBe(200);
    expect(pantryRes.statusCode).toBe(200);
    expect(healthRes.statusCode).toBe(200);
    expect(tasteRes.statusCode).toBe(200);

    const defaultBody = JSON.parse(defaultRes.body) as {
      context: { view: string };
      recommendations: Array<{ recipeId: string; parts: Record<string, number> }>;
    };
    const pantryBody = JSON.parse(pantryRes.body) as {
      context: { view: string };
      recommendations: Array<{ recipeId: string; parts: Record<string, number> }>;
    };
    const healthBody = JSON.parse(healthRes.body) as {
      context: { view: string };
      recommendations: Array<{ recipeId: string; parts: Record<string, number> }>;
    };
    const tasteBody = JSON.parse(tasteRes.body) as {
      context: { view: string };
      recommendations: Array<{ recipeId: string; parts: Record<string, number> }>;
    };

    // Vyn honoreras i svaret även utan samtycke.
    expect(defaultBody.context.view).toBe("default");
    expect(pantryBody.context.view).toBe("pantry");
    expect(healthBody.context.view).toBe("health");
    expect(tasteBody.context.view).toBe("taste");

    // Personliga axlar är nollade i alla vyer utan samtycke.
    for (const body of [defaultBody, pantryBody, healthBody, tasteBody]) {
      for (const rec of body.recommendations) {
        expect(rec.parts.memoryFit ?? 0).toBe(0);
        expect(rec.parts.tasteFit ?? 0).toBe(0);
        expect(rec.parts.cookingAssumptionFit ?? 0).toBe(0);
      }
    }
  });

  it("default-vyn är oförändrad med och utan samtycke", async () => {
    // Se till att samtycke är revoked.
    await testDb.db
      .insert(schema.userConsents)
      .values({ userId, kind: "personalization", status: "revoked" })
      .onConflictDoUpdate({
        target: [schema.userConsents.userId, schema.userConsents.kind],
        set: { status: "revoked" },
      });

    const withoutConsent = await app.inject({
      method: "GET",
      url: "/v1/recommendations/what-to-eat?view=default&limit=5",
      headers: { authorization: `Bearer ${accessToken}` },
    });

    await testDb.db
      .insert(schema.userConsents)
      .values({ userId, kind: "personalization", status: "granted" })
      .onConflictDoUpdate({
        target: [schema.userConsents.userId, schema.userConsents.kind],
        set: { status: "granted" },
      });

    const withConsent = await app.inject({
      method: "GET",
      url: "/v1/recommendations/what-to-eat?view=default&limit=5",
      headers: { authorization: `Bearer ${accessToken}` },
    });

    expect(withoutConsent.statusCode).toBe(200);
    expect(withConsent.statusCode).toBe(200);

    const a = JSON.parse(withoutConsent.body) as {
      recommendations: Array<{ recipeId: string }>;
    };
    const b = JSON.parse(withConsent.body) as {
      recommendations: Array<{ recipeId: string }>;
    };

    expect(a.recommendations.map((r) => r.recipeId)).toEqual(
      b.recommendations.map((r) => r.recipeId),
    );
  });
});
