const express = require('express');

module.exports = function(ctx) {
  const router = express.Router();

  // Activate a license code
  router.post('/activate', ctx.asyncHandler(async (req, res) => {
    const { code } = req.body;
    if (!code) {
      return ctx.errorResponse(res, 400, 'License code is required');
    }

    const result = await ctx.licenseManager.activate(code);

    if (result.success) {
      res.json({
        success: true,
        message: result.message,
        license: result.activation
      });
    } else {
      ctx.errorResponse(res, 400, result.message);
    }
  }, 'license-activate'));

  // Get current license status
  router.get('/status', ctx.asyncHandler(async (req, res) => {
    const status = ctx.licenseManager.getStatus();
    res.json({ success: true, license: status });
  }, 'license-status'));

  // Deactivate current license
  router.post('/deactivate', ctx.asyncHandler(async (req, res) => {
    const result = await ctx.licenseManager.deactivate();

    if (result.success) {
      res.json({ success: true, message: result.message });
    } else {
      ctx.errorResponse(res, 400, result.message);
    }
  }, 'license-deactivate'));

  // Check if a specific feature is available (lightweight check for frontend)
  router.get('/feature/:feature', ctx.asyncHandler(async (req, res) => {
    const { feature } = req.params;
    const available = ctx.licenseManager.hasFeature(feature);
    const status = ctx.licenseManager.getStatus();

    res.json({
      success: true,
      feature,
      available,
      tier: status.tier,
      ...(available ? {} : {
        upgradeUrl: '/settings#license',
        message: `${status.premiumFeatures[feature]?.name || feature} requires DashCaddy Premium`
      })
    });
  }, 'license-feature-check'));

  return router;
};
