import { {{MODULE.SERVICE.CLASS_NAME}} } from './{{SUB_MODULE_DOT_ENTITY_KEBABCASED_PLURAL}}.service';
import { Router, Request, Response, NextFunction } from 'express';
import initLogger, { LoggerContext } from "jsm-logger";
import Container from 'typedi';
import { respond, getAuthData } from 'jsm-utilities';

/**
 * Logger instance
 */
const logger = initLogger(LoggerContext.CONTROLLER, '{{SUB_MODULE_ENTITY_CAMELCASED_PLURAL}}');

/**
 * @module {{MODULE.CONTROLLER.CLASS_NAME}}
 * @description {{MODULE.CONTROLLER.DESCRIPTION}} controller
 * @param {Router} router
 * @returns {void}
 */
export default (router: Router) => {

  logger.event('Loading module controller');
  
  const service = Container.get({{MODULE.SERVICE.CLASS_NAME}});
  
  // Module health check endpoint
  router.get(
    '/health',
    async (req: Request, res: Response, next: NextFunction) => {
      try {
        respond(res, {
          status: 'ok',
          module: service.ENTITY,
          message: 'Service is healthy'
        });
      } catch (error) {
        next(error);
      }
    }
  );


  // Loop through each API method and create the corresponding route handler
  {{#each MODULE.API.METHODS}}
    /**
     * @function {{this.name}}
     * @description {{this.description}}
     * @param {Request} req
     * @param {Response} res
     * @param {NextFunction} next
     */
    {{#each this.meta.links}}
      router.{{lowercase ../this.meta.method}}(
        '{{this.path}}',
        async (req: Request, res: Response, next: NextFunction) => {
          try {
            /**
            * Always get the auth data at the beginning of the function
            */
            const AUTH_DATA = await getAuthData(req);

            {{controllerMethodParams ../this this}}
            const response = await service.{{this.fires.method}}({{controllerMethodArgs ../this this}});
            respond<R>(res, response);
          } catch (error) {
            /**
             * Pass the error to the next middleware
             * the error logging logic is handled on the service layer
             */
            next(error);
          }
        }
      );
      {{nl}}
    {{/each}}
  {{/each}}
};

