import { describe, expect, it } from "vitest";
import { openDatabase } from "../src/core/db.js";
import { PurchasePlanRepository, PurchasePlanSchema } from "../src/core/purchasePlan.js";
import type { PurchasePlan } from "../shared/contract.js";

const emptyPlan: PurchasePlan = { schemaVersion: 1, storeSort: "lines", requirements: [] };

describe("PurchasePlanRepository", () => {
  it("stores one shared plan and replaces it on later writes", () => {
    const db = openDatabase(":memory:");
    const repository = new PurchasePlanRepository(db);
    expect(repository.get()).toBeNull();

    repository.set(emptyPlan, 100);
    expect(repository.get()).toEqual({ plan: emptyPlan, updatedAt: 100 });

    const updated: PurchasePlan = { ...emptyPlan, storeSort: "subtotal" };
    repository.set(updated, 200);
    expect(repository.get()).toEqual({ plan: updated, updatedAt: 200 });
    db.close();
  });

  it("rejects malformed documents and inconsistent candidate selections", () => {
    expect(PurchasePlanSchema.safeParse({ schemaVersion: 2, storeSort: "lines", requirements: [] }).success).toBe(false);
    expect(PurchasePlanSchema.safeParse({
      schemaVersion: 1,
      storeSort: "lines",
      requirements: [{
        id: "r1",
        partKey: "MANN|W71252",
        brand: "MANN",
        partNumber: "W71252",
        title: "Filter",
        imageUrl: null,
        quantity: 1,
        chosenCandidateId: "missing",
        candidates: [],
      }],
    }).success).toBe(false);
  });
});
