// @ts-nocheck
import test from "node:test";
import assert from "node:assert/strict";
import { assertReadOnlySql } from "../src/lib/sql-readonly.ts";
import { assertAllowedWriteSql } from "../src/lib/sql-write-allowlist.ts";
import {
  catalogMakerSql,
  mappingSourceTablesSql,
  mappingSourcesSql,
  prepareManufacturerCatalogSqls,
  productByEanSql,
  productCombinationInfoSql,
  productCombinationsByReferenceSql,
  productToDoByManufacturerSql,
} from "../src/sql/catalog-maker.ts";

test("manufacturer query is read-only", () => {
  assert.doesNotThrow(() => assertReadOnlySql(catalogMakerSql.manufacturers));
});

test("languages query is read-only", () => {
  assert.doesNotThrow(() => assertReadOnlySql(catalogMakerSql.languages));
});

test("product to-do query is read-only", () => {
  assert.doesNotThrow(() =>
    assertReadOnlySql(productToDoByManufacturerSql({ manufacturerId: 13, position: 1 })),
  );
});

test("product combinations query is read-only", () => {
  assert.doesNotThrow(() =>
    assertReadOnlySql(
      productCombinationsByReferenceSql({ manufacturerId: 13, supplierReference: "TEST" }),
    ),
  );
});

test("product combination info query is read-only", () => {
  assert.doesNotThrow(() =>
    assertReadOnlySql(
      productCombinationInfoSql({
        productId: 135520,
        manufacturerId: 13,
        supplierReference: "ZFHS099",
      }),
    ),
  );
});

test("product by EAN query is read-only", () => {
  assert.doesNotThrow(() =>
    assertReadOnlySql(productByEanSql({ manufacturerId: 13, ean: "8058428191321" })),
  );
});

test("mapping source queries are read-only", () => {
  assert.doesNotThrow(() => assertReadOnlySql(mappingSourceTablesSql()));
  assert.doesNotThrow(() =>
    assertReadOnlySql(mappingSourcesSql({ manufacturerId: 13 })),
  );
  assert.match(mappingSourcesSql({ manufacturerId: 13 }), /scrape_manufacturer_sources/);
  assert.match(mappingSourcesSql({ manufacturerId: 13 }), /scrape_source_capabilities/);
  assert.match(mappingSourcesSql({ manufacturerId: 13 }), /capabilities/);
});

test("manufacturer refresh updates are narrowly allowlisted", () => {
  for (const sql of prepareManufacturerCatalogSqls({ manufacturerId: 13 })) {
    assert.doesNotThrow(() =>
      assertAllowedWriteSql(sql, { operation: "catalog-maker-refresh-manufacturer" }),
    );
  }
});

test("random update remains blocked", () => {
  assert.throws(
    () =>
      assertAllowedWriteSql("UPDATE ps_product SET price = 0 WHERE id_product = 1", {
        operation: "catalog-maker-refresh-manufacturer",
      }),
    /allowlist/,
  );
});
