/**
 * Behebt "Right-hand side of 'instanceof' is not callable" bei json-bigint.
 * Beim Vite-Build liefert require('bignumber.js') bei ESM-Alias das Modul-Objekt
 * { default: BigNumber }; json-bigint nutzt aber "value instanceof BigNumber".
 * Wir setzen BigNumber auf den echten Konstruktor (default-Export), falls vorhanden.
 */
const DEFAULT_EXTRACT =
  "\nif (typeof BigNumber === 'object' && BigNumber && typeof BigNumber.default === 'function') BigNumber = BigNumber.default;";

export function jsonBigintBigNumberFix() {
  return {
    name: "json-bigint-bignumber-fix",
    enforce: "pre",
    transform(src, id) {
      const idNorm = id.replace(/\\/g, "/");
      if (!idNorm.includes("json-bigint")) return null;
      const isStringify = idNorm.includes("stringify.js");
      const isParse = idNorm.includes("parse.js");
      if (!isStringify && !isParse) return null;

      if (isStringify) {
        const firstLine = "var BigNumber = require('bignumber.js');";
        if (!src.includes(firstLine)) return null;
        return {
          code: src.replace(firstLine, firstLine + DEFAULT_EXTRACT),
          map: null,
        };
      }

      if (isParse) {
        const requireLine =
          "if (BigNumber == null) BigNumber = require('bignumber.js');";
        if (!src.includes(requireLine)) return null;
        return {
          code: src.replace(requireLine, requireLine + DEFAULT_EXTRACT),
          map: null,
        };
      }

      return null;
    },
  };
}
