'use strict';

const express = require('express');
const router = express.Router();
const billingPrint = require('../modules/billing-print');
const { requirePermission } = require('../middleware/permissions');

router.post('/reload-entitlements', requirePermission('billing.configure'), async (_req, res, next) => {
  try {
    res.json(await billingPrint.bootstrap.reloadEntitlements());
  } catch (err) {
    next(err);
  }
});

router.post('/provision', async (req, res, next) => {
  try {
    const { provisionWithClaimCode, provisionWithControlNumber } = require('../agent/provisioningClient');
    const { claimCode, controlNumber, controlPassword, cloudUrl } = req.body || {};
    const normalizedClaim = String(claimCode || '').trim().toUpperCase();
    const result = normalizedClaim
      ? await provisionWithClaimCode({ claimCode: normalizedClaim, cloudUrl })
      : await provisionWithControlNumber({ controlNumber, controlPassword, cloudUrl });
    res.json({ ok: true, ...result });
  } catch (err) {
    next(err);
  }
});

module.exports = router;
