import assert from "node:assert/strict";
import { describe, it } from "node:test";
import { readFileSync } from "node:fs";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";

const __dirname = dirname(fileURLToPath(import.meta.url));
const source = readFileSync(join(__dirname, "ProductSpecLiteView.vue"), "utf8");

describe("ProductSpecLiteView operation foundation loading", () => {
  it("loads process and work-center master data sequentially so backend default seeding can settle", () => {
    assert.match(source, /const processRows = await fetchResource\("\/master-data\/processes", \[\]\);/);
    assert.match(source, /const centerRows = await fetchResource\("\/master-data\/work-centers", \[\]\);/);
    assert.ok(
      source.indexOf('fetchResource("/master-data/processes", [])') <
        source.indexOf('fetchResource("/master-data/work-centers", [])')
    );
  });

  it("prepares route operations before creating a new product so validation cannot leave partial records", () => {
    assert.match(source, /async function ensureOperationFoundationReady\(\)/);
    assert.match(source, /await ensureOperationFoundationReady\(\);/);
    assert.match(source, /const preparedRouteOperations = buildRouteOperationsPayload\(processRowsForSave\);/);
    assert.ok(
      source.indexOf("const preparedRouteOperations = buildRouteOperationsPayload(processRowsForSave);") <
        source.indexOf('await postResource("/master-data/products", productPayload)')
    );
  });

  it("cleans newly created product-spec records if a later save step fails", () => {
    assert.match(source, /let createdProductItemId = null;/);
    assert.match(source, /const createdMiniappPayloads = \[\];/);
    assert.match(source, /createdProductItemId = productItemId;/);
    assert.match(source, /createdMiniappPayloads\.push\(payload\);/);
    assert.match(source, /await deleteResource\(buildMiniappDeletePath\(payload\)\)\.catch\(\(\) => null\);/);
    assert.match(source, /await deleteResource\(`\/master-data\/product-specs\/\$\{createdProductItemId\}`\)\.catch\(\(\) => null\);/);
  });

  it("does not override wide mode with a product-spec-only one-screen table layout", () => {
    assert.doesNotMatch(source, /product-spec-table-wrap/);
    assert.doesNotMatch(source, /product-spec-table/);
    assert.doesNotMatch(source, /<colgroup>[\s\S]*product-spec-col-action[\s\S]*<\/colgroup>/);
    assert.doesNotMatch(source, /overflow-x:\s*hidden !important/);
    assert.doesNotMatch(source, /table-layout:\s*fixed !important;[\s\S]*product-spec/);
  });
});
