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("uses a one-screen table layout so the action and pagination areas do not get pushed into the edge", () => {
    assert.match(source, /class="table-wrap product-spec-table-wrap"/);
    assert.match(source, /class="data-table compact-table product-spec-table"/);
    assert.match(source, /<colgroup>[\s\S]*product-spec-col-action[\s\S]*<\/colgroup>/);
    assert.match(source, /\.product-spec-table-wrap\.table-view-wide,[\s\S]*?overflow-x:\s*hidden !important;/);
    assert.match(source, /\.product-spec-table[\s\S]*?table-layout:\s*fixed !important;/);
    assert.match(source, /\.product-spec-table\s+\.action-row[\s\S]*?width:\s*100% !important;/);
  });
});
