import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import vm from "node:vm";
import { fileURLToPath } from "node:url";

const source = readFileSync(
  fileURLToPath(new URL("../src/views/InventoryLedgerView.vue", import.meta.url)),
  "utf8"
);

const functionStart = source.indexOf("function computeWorkOrderSourceLotReturnLimit");
const nextFunctionStart = source.indexOf("function productionSurplusReturnInputMax", functionStart);
assert.ok(functionStart >= 0 && nextFunctionStart > functionStart, "should find source lot return limit function");
const inputMaxStart = nextFunctionStart;
const nextApplyFunctionStart = source.indexOf("function applyGenericWorkOrder", inputMaxStart);
assert.ok(nextApplyFunctionStart > inputMaxStart, "should find production surplus input max function");

const functionSource = source.slice(functionStart, nextFunctionStart);
const sandbox = {};
vm.createContext(sandbox);
vm.runInContext(`${functionSource}; globalThis.computeWorkOrderSourceLotReturnLimit = computeWorkOrderSourceLotReturnLimit;`, sandbox);

const workOrder = {
  limits: {
    issued_weight_kg: 200,
    used_material_weight_kg: 61.8,
    returned_material_weight_kg: 0,
    max_surplus_inbound_weight_kg: 138.2,
    tolerance_surplus_inbound_weight_kg: 158.93
  }
};
const material = {
  issued_weight_kg: 100,
  returned_weight_kg: 0
};

const limit = sandbox.computeWorkOrderSourceLotReturnLimit(workOrder, material);

assert.equal(limit.normal, 69.1, "single lot normal return limit should subtract its proportional used material weight");
assert.equal(limit.tolerance, 79.465, "single lot tolerance limit should also use its proportional remaining weight");

const inputMaxSource = source.slice(inputMaxStart, nextApplyFunctionStart);
assert.doesNotMatch(
  inputMaxSource,
  /Math\.min\([\s\S]*tolerance_return_weight_kg/,
  "single lot input max should not block uneven returns with the proportional suggested return weight"
);
assert.match(
  inputMaxSource,
  /source_remaining_weight_kg/,
  "single lot input max should only cap by the source lot's unreturned issued weight"
);
assert.match(
  source,
  /:disabled="productionSurplusReturnInputDisabled\(lot\)"/,
  "fully returned production surplus source lots should disable the return input instead of showing a min/max browser warning"
);
assert.match(
  source,
  /function productionSurplusReturnInputDisabled\(lot\)/,
  "production surplus inbound should have an explicit disabled helper for fully returned source lots"
);
assert.match(
  source,
  /const sourceLotsToSubmit = selectedGenericSourceLots\.value\.filter/,
  "production surplus inbound should submit only source lots with an actual positive return weight"
);

console.log("production surplus source lot return limit checks passed");
