import assert from "node:assert/strict";
import fs from "node:fs";
import path from "node:path";

const root = process.cwd();
const styles = fs.readFileSync(path.join(root, "src/styles/main.css"), "utf8");
const inventory = fs.readFileSync(path.join(root, "src/views/InventoryLedgerView.vue"), "utf8");

function blockFor(selector) {
  const escaped = selector.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
  const match = styles.match(new RegExp(`${escaped}\\s*\\{([\\s\\S]*?)\\}`));
  assert.ok(match, `missing style block for ${selector}`);
  return match[1];
}

const workflowTableWrap = blockFor(".workflow-drawer .table-wrap");
assert.match(
  workflowTableWrap,
  /overflow-x:\s*auto/,
  "drawer table wrappers must allow horizontal scrolling instead of clipping overflow"
);
assert.doesNotMatch(
  workflowTableWrap,
  /overflow-x:\s*hidden/,
  "drawer table wrappers must not hide overflowing columns"
);

const drawerDataTableWrap = blockFor(".drawer-data-table-wrap");
assert.match(
  drawerDataTableWrap,
  /overflow-x:\s*auto/,
  "DrawerDataTable wrapper must allow horizontal scrolling"
);
assert.doesNotMatch(
  drawerDataTableWrap,
  /overflow:\s*hidden|overflow-x:\s*hidden/,
  "DrawerDataTable wrapper must not clip columns"
);

const workflowTable = blockFor(".workflow-drawer .data-table");
assert.match(
  workflowTable,
  /width:\s*max-content/,
  "drawer tables should size to their columns when wider than the drawer"
);
assert.match(
  workflowTable,
  /min-width:\s*100%/,
  "drawer tables should still fill the drawer when columns are narrow"
);
assert.match(
  workflowTable,
  /table-layout:\s*auto/,
  "drawer tables should not use fixed layout that squeezes headers and cells"
);

const drawerDataTable = blockFor(".drawer-data-table");
assert.match(
  drawerDataTable,
  /width:\s*max-content/,
  "DrawerDataTable should size to column widths when needed"
);
assert.match(
  drawerDataTable,
  /min-width:\s*100%/,
  "DrawerDataTable should still fill the available drawer width"
);
assert.match(
  drawerDataTable,
  /table-layout:\s*auto/,
  "DrawerDataTable should not use fixed layout that cuts off trailing columns"
);

assert.match(
  inventory,
  /<DrawerDataTable[\s\S]*:columns="lotDrawerColumns"/,
  "warehouse lot details should use DrawerDataTable and benefit from the overflow fix"
);
assert.match(
  inventory,
  /<DrawerDataTable[\s\S]*:columns="txnDrawerColumns"/,
  "warehouse transaction details should use DrawerDataTable and benefit from the overflow fix"
);

console.log("warehouse drawer table overflow checks passed");
