import MemoryBudgetError from "../errors/MemoryBudgetError.js";
import { requireMemoryBudgetUnit } from "./MemoryBudgetUnit.js";
/** Runtime lease against a WarpMemoryPool budget. */
export default class MemoryBudgetLease {
    id;
    name;
    scope;
    amount;
    unit;
    _releaseLease;
    constructor(fields) {
        const validFields = requireMemoryBudgetLeaseFields(fields);
        this.id = requireNonEmptyString(validFields.id, 'id');
        this.name = requireNonEmptyString(validFields.name, 'name');
        this.scope = requireNonEmptyString(validFields.scope, 'scope');
        this.amount = requirePositiveInteger(validFields.amount, 'amount');
        this.unit = requireMemoryBudgetUnit(validFields.unit);
        this._releaseLease = requireReleaseLease(validFields.releaseLease);
        Object.freeze(this);
    }
    release() {
        this._releaseLease(this.id);
    }
}
function requireMemoryBudgetLeaseFields(fields) {
    if (fields !== null && typeof fields === 'object') {
        return fields;
    }
    throw new MemoryBudgetError('MemoryBudgetLease requires object fields', {
        code: 'E_MEMORY_BUDGET_INVALID',
        context: { field: 'fields' },
    });
}
function requireReleaseLease(value) {
    if (typeof value === 'function') {
        return value;
    }
    throw new MemoryBudgetError('Memory budget lease requires a release function', {
        code: 'E_MEMORY_BUDGET_INVALID',
        context: { field: 'releaseLease' },
    });
}
function requireNonEmptyString(value, field) {
    if (typeof value === 'string' && value.trim().length > 0) {
        return value;
    }
    throw new MemoryBudgetError('Memory budget lease requires non-empty identity fields', {
        code: 'E_MEMORY_BUDGET_INVALID',
        context: { field },
    });
}
function requirePositiveInteger(value, field) {
    if (Number.isInteger(value) && value > 0) {
        return value;
    }
    throw new MemoryBudgetError('Memory budget lease amount must be a positive integer', {
        code: 'E_MEMORY_BUDGET_INVALID',
        context: { field, value },
    });
}
