import { describe, expect, it } from "vitest";
import { dropLegacyMeasurementTables, openDatabase } from "../src/core/db.js";
import { SearchHistoryRepository, SearchHistorySchema } from "../src/core/searchHistory.js";
import type { SearchHistory } from "../shared/contract.js";

const history: SearchHistory = {
  schemaVersion: 1,
  entries: [
    { query: "W 712/52", canonical: "W71252", searchedAt: 2000 },
    { query: "09.C881.11", canonical: "09C88111", searchedAt: 1000 },
  ],
};

describe("SearchHistoryRepository", () => {
  it("persists one shared history document and timestamp", () => {
    const repository = new SearchHistoryRepository(openDatabase(":memory:"));
    expect(repository.get()).toBeNull();
    expect(repository.set(history, 3000)).toBe(3000);
    expect(repository.get()).toEqual({ history, updatedAt: 3000 });
  });

  it("rejects duplicates, mismatched canonical values, and non-recency ordering", () => {
    expect(SearchHistorySchema.safeParse({
      schemaVersion: 1,
      entries: [
        { query: "W71252", canonical: "wrong", searchedAt: 1 },
      ],
    }).success).toBe(false);
    expect(SearchHistorySchema.safeParse({
      schemaVersion: 1,
      entries: [history.entries[1], history.entries[0]],
    }).success).toBe(false);
    expect(SearchHistorySchema.safeParse({
      schemaVersion: 1,
      entries: [history.entries[0], { ...history.entries[0], query: "W71252" }],
    }).success).toBe(false);
  });
});

describe("measurement removal migration", () => {
  it("drops every legacy measurement table and its retained records", () => {
    const db = openDatabase(":memory:");
    db.exec(`
      CREATE TABLE searches (id INTEGER);
      CREATE TABLE search_results (id INTEGER);
      CREATE TABLE clickouts (id INTEGER);
      INSERT INTO searches VALUES (1);
    `);
    dropLegacyMeasurementTables(db);
    const tables = db.prepare("SELECT name FROM sqlite_master WHERE type = 'table'").all() as { name: string }[];
    expect(tables.map((table) => table.name)).not.toEqual(expect.arrayContaining(["searches", "search_results", "clickouts"]));
  });
});
