import { getBillingCatalogPlan, getBillingCatalogStorageAddOn, type StorageAddOnCode } from "./commercial-catalog.js"; export const STORAGE_BYTES_PER_GB = 1024 * 1024 * 1024; export type StorageCapacitySelection = { readonly planCode: string; readonly officeSeatQuantity: number; readonly fieldSeatQuantity: number; readonly storageAddOnCodes?: readonly (StorageAddOnCode | string)[]; }; export type StorageCapacity = { readonly planCode: string; readonly includedStorageGb: number; readonly additionalSeatStorageGb: number; readonly addOnStorageGb: number; readonly totalStorageGb: number; readonly totalStorageBytes: number; }; function requireSeatQuantity(value: number, label: string): number { if (!Number.isSafeInteger(value) || value < 0 || value > 10_000) { throw new RangeError(`${label} must be a non-negative safe integer up to 10000.`); } return value; } function safeStorageBytes(totalStorageGb: number): number { const bytes = totalStorageGb * STORAGE_BYTES_PER_GB; if (!Number.isSafeInteger(bytes) || bytes < 0) { throw new RangeError("Storage capacity exceeds the safe integer range."); } return bytes; } export function calculateStorageCapacity(selection: StorageCapacitySelection): StorageCapacity { const plan = getBillingCatalogPlan(selection.planCode); if (!plan) throw new RangeError(`Unknown billing plan: ${selection.planCode}`); const officeSeatQuantity = requireSeatQuantity(selection.officeSeatQuantity, "officeSeatQuantity"); const fieldSeatQuantity = requireSeatQuantity(selection.fieldSeatQuantity, "fieldSeatQuantity"); const storageAddOnCodes = selection.storageAddOnCodes ?? []; if (new Set(storageAddOnCodes).size !== storageAddOnCodes.length) { throw new RangeError("Storage add-on codes must be unique."); } const addOnStorageGb = storageAddOnCodes.reduce((total, code) => { const addOn = getBillingCatalogStorageAddOn(code); if (!addOn) throw new RangeError(`Unknown storage add-on: ${code}`); return total + addOn.includedStorageGb; }, 0); const additionalSeatQuantity = Math.max(0, officeSeatQuantity - plan.includedSeats.office) + Math.max(0, fieldSeatQuantity - plan.includedSeats.field); const additionalSeatStorageGb = additionalSeatQuantity * plan.storagePerAdditionalSeatGb; const totalStorageGb = plan.includedStorageGb + additionalSeatStorageGb + addOnStorageGb; return Object.freeze({ planCode: plan.technicalCode, includedStorageGb: plan.includedStorageGb, additionalSeatStorageGb, addOnStorageGb, totalStorageGb, totalStorageBytes: safeStorageBytes(totalStorageGb), }); }