const express = require('express');
const initHelpers = require('./helpers');
const initDeploy = require('./deploy');
const initRemoval = require('./removal');
const initTemplates = require('./templates');
const initRestore = require('./restore');
const initCompose = require('./compose');

/**
 * Apps routes aggregator
 * Assembles all apps sub-routes with their dependencies
 * @param {Object} ctx - Application context (for backward compatibility)
 * @returns {express.Router}
 */
module.exports = function(ctx) {
  const router = express.Router();

  // Extract dependencies from context
  const deps = {
    docker: ctx.docker,
    caddy: ctx.caddy,
    credentialManager: ctx.credentialManager,
    servicesStateManager: ctx.servicesStateManager,
    portLockManager: ctx.portLockManager,
    asyncHandler: ctx.asyncHandler,
    errorResponse: ctx.errorResponse,
    log: ctx.log,
    APP_TEMPLATES: ctx.APP_TEMPLATES,
    TEMPLATE_CATEGORIES: ctx.TEMPLATE_CATEGORIES,
    DIFFICULTY_LEVELS: ctx.DIFFICULTY_LEVELS,
    siteConfig: ctx.siteConfig,
    buildDomain: ctx.buildDomain,
    buildServiceUrl: ctx.buildServiceUrl,
    addServiceToConfig: ctx.addServiceToConfig,
    dns: ctx.dns,
    notification: ctx.notification,
    safeErrorMessage: ctx.safeErrorMessage,
    SERVICES_FILE: ctx.SERVICES_FILE,
    ctx: ctx
  };

  const helpers = initHelpers({ ...deps, ctx });
  const subCtx = Object.assign({}, ctx, { helpers });

  // Mount sub-routers at their prefix paths.
  // Sub-modules define routes at '/' (root of their sub-router).
  // Final paths: /api/v1/apps/deploy, /api/v1/apps/remove, /api/v1/apps/templates, etc.

  try { router.use('/apps', initDeploy(subCtx)); }
  catch(e) { (ctx.log || console).error('[apps] deploy routes init failed:', e.message, e.stack); }

  try { router.use('/apps', initRemoval(subCtx)); }
  catch(e) { (ctx.log || console).error('[apps] removal routes init failed:', e.message, e.stack); }

  try { router.use('/apps', initTemplates(subCtx)); }
  catch(e) { (ctx.log || console).error('[apps] templates routes init failed:', e.message, e.stack); }

  try { router.use('/apps', initRestore(Object.assign({}, subCtx, { backupManager: ctx.backupManager }))); }
  catch(e) { (ctx.log || console).error('[apps] restore routes init failed:', e.message, e.stack); }

  try { router.use('/apps', initCompose(subCtx)); }
  catch(e) { (ctx.log || console).error('[apps] compose routes init failed:', e.message, e.stack); }

  return router;
};
