import { beforeEach, describe, expect, it } from "vitest";
import { db } from "../db";
import { keywordSets, settings } from "../db/schema";
import {
  activateKeywordSet,
  createKeywordSet,
  ensureKeywordSetsForOwner,
  getActiveKeywordSetTerms,
  listKeywordSets,
  syncActiveKeywordSetTerms,
} from "./keyword-sets";

const OWNER = "__test_keyword_sets__";

describe("keyword-sets repository", () => {
  beforeEach(async () => {
    await db.delete(keywordSets);
    await db.delete(settings);
  });

  it("creates a default set for a new owner", async () => {
    await ensureKeywordSetsForOwner(OWNER);
    const sets = await listKeywordSets(OWNER);
    expect(sets).toHaveLength(1);
    expect(sets[0]?.name).toBe("Default");
    expect(sets[0]?.isActive).toBe(true);
  });

  it("activates a set and returns its terms for discovery", async () => {
    const first = await createKeywordSet(OWNER, {
      name: "SDET",
      terms: ["sdet", "playwright"],
    });
    const second = await createKeywordSet(OWNER, {
      name: "Lead",
      terms: ["engineering manager"],
    });
    await activateKeywordSet(second.id, OWNER);
    const terms = await getActiveKeywordSetTerms(OWNER);
    expect(terms).toEqual(["engineering manager"]);
    await activateKeywordSet(first.id, OWNER);
    expect(await getActiveKeywordSetTerms(OWNER)).toEqual([
      "sdet",
      "playwright",
    ]);
  });

  it("syncs terms on the active set", async () => {
    await ensureKeywordSetsForOwner(OWNER);
    const sets = await listKeywordSets(OWNER);
    const activeId = sets[0]?.id;
    expect(activeId).toBeTruthy();
    await syncActiveKeywordSetTerms(OWNER, ["caseware", "guidewire"]);
    expect(await getActiveKeywordSetTerms(OWNER)).toEqual([
      "caseware",
      "guidewire",
    ]);
  });
});
