import { beforeEach, describe, expect, it, vi } from "vitest";

const supabaseMock = vi.hoisted(() => {
  process.env.SUPABASE_URL = "https://example.supabase.co";
  process.env.SUPABASE_SERVICE_ROLE_KEY = "test-key";
  return {
    from: vi.fn(),
  };
});

vi.mock("@supabase/supabase-js", () => ({
  createClient: vi.fn(() => supabaseMock),
}));

import { upsertProcurementDictionaryEntries } from "./db.ts";

function mockDictionaryTable(existing: { id: string } | null, insertError: unknown = null) {
  const query = {
    eq: vi.fn(() => query),
    maybeSingle: vi.fn(async () => ({ data: existing, error: null })),
  };
  const table = {
    select: vi.fn(() => query),
    insert: vi.fn(async () => ({ error: insertError })),
    update: vi.fn(),
  };
  supabaseMock.from.mockReturnValue(table);
  return { query, table };
}

describe("procurement dictionary dedupe", () => {
  beforeEach(() => {
    vi.clearAllMocks();
  });

  it("silently skips an existing normalized term/type/context without updating it", async () => {
    const { query, table } = mockDictionaryTable({ id: "entry-1" });

    await upsertProcurementDictionaryEntries([
      {
        term: " geb371  ",
        term_type: "unique_model",
        product_context: " 电池   配件 ",
        interpretation: "外挂电池",
        evidence: "test",
      },
    ]);

    expect(table.select).toHaveBeenCalledWith("id");
    expect(query.eq).toHaveBeenNthCalledWith(1, "normalized_term", "GEB371");
    expect(query.eq).toHaveBeenNthCalledWith(2, "term_type", "unique_model");
    expect(query.eq).toHaveBeenNthCalledWith(3, "normalized_context", "电池 配件");
    expect(table.update).not.toHaveBeenCalled();
    expect(table.insert).not.toHaveBeenCalled();
  });

  it("treats concurrent unique constraint conflicts as duplicate no-ops", async () => {
    const { table } = mockDictionaryTable(null, {
      code: "23505",
      message: "duplicate key value violates unique constraint",
      details: "procurement_dictionary_entries_unique_term_context",
    });

    await expect(upsertProcurementDictionaryEntries([
      {
        term: "GEB371",
        term_type: "unique_model",
        product_context: "",
        interpretation: "外挂电池",
        evidence: "test",
      },
    ])).resolves.toBeUndefined();

    expect(table.insert).toHaveBeenCalledTimes(1);
    expect(table.update).not.toHaveBeenCalled();
  });
});
