/**
 * Swagger/OpenAPI Documentation Configuration
 * API documentation setup using swagger-jsdoc and swagger-ui-express
 */

// Skip Swagger setup in test environment - export no-op function
if (process.env.NODE_ENV === 'test') {
  // Export a no-op function for test environment
  module.exports = () => {}; // Return empty function, do nothing
} else {
  // Import swagger-jsdoc for generating OpenAPI specification
  const swaggerJsdoc = require('swagger-jsdoc');
  // Import swagger-ui-express for serving Swagger UI
  const swaggerUi = require('swagger-ui-express');
  // Import app configuration
  const appConfig = require('./config/app');

  /**
   * Swagger definition options
   * Defines the basic API information
   */
  const swaggerDefinition = {
    openapi: '3.0.0', // OpenAPI specification version
    info: {
      title: 'Smart POS API', // API title
      version: '1.0.0', // API version
      description: 'Smart POS + Inventory + Production + KRA eTIMS Backend API Documentation', // API description
      contact: {
        name: 'API Support', // Contact name
        email: 'support@xyzpos.com', // Contact email
      },
      license: {
        name: 'ISC', // License name
        url: 'https://opensource.org/licenses/ISC', // License URL
      },
    },
    servers: [
      {
        url: `http://${appConfig.server.host}:${appConfig.server.port}/api`, // Development server URL
        description: 'Development server', // Server description
      },
      {
        url: 'https://api.xyzpos.com/api', // Production server URL (example)
        description: 'Production server', // Server description
      },
    ],
    components: {
      securitySchemes: {
        bearerAuth: {
          type: 'http', // Authentication type
          scheme: 'bearer', // Bearer token scheme
          bearerFormat: 'JWT', // JWT token format
          description: 'JWT token obtained from login endpoint', // Authentication description
        },
      },
      schemas: {
        // Common response schemas
        SuccessResponse: {
          type: 'object', // Response object type
          properties: {
            success: {
              type: 'boolean', // Success flag type
              example: true, // Example value
            },
            message: {
              type: 'string', // Message type
              example: 'Operation successful', // Example message
            },
            data: {
              type: 'object', // Data object type (can be any)
            },
          },
        },
        ErrorResponse: {
          type: 'object', // Error response object type
          properties: {
            success: {
              type: 'boolean', // Success flag type
              example: false, // Example value
            },
            message: {
              type: 'string', // Error message type
              example: 'An error occurred', // Example error message
            },
            errors: {
              type: 'array', // Errors array type
              items: {
                type: 'object', // Error item type
              },
            },
          },
        },
      },
    },
    security: [
      {
        bearerAuth: [], // Default security requirement (JWT)
      },
    ],
  };

  /**
   * Swagger options
   * Configuration for swagger-jsdoc
   */
  const swaggerOptions = {
    definition: swaggerDefinition, // Swagger definition
    apis: [
      './routes/*.js', // Path to API route files
      './modules/*/routes/*.js', // Path to module route files
      './modules/*/controllers/*.js', // Path to controller files (for JSDoc comments)
    ],
  };

  /**
   * Generate Swagger specification
   * Parse JSDoc comments and generate OpenAPI spec
   */
  const swaggerSpec = swaggerJsdoc(swaggerOptions);

  /**
   * Swagger setup function
   * Sets up Swagger UI middleware
   * @param {Object} app - Express application instance
   */
  const setupSwagger = (app) => {
    // Serve Swagger UI at /api-docs
    app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerSpec, {
      customCss: '.swagger-ui .topbar { display: none }', // Hide Swagger topbar
      customSiteTitle: 'Smart POS API Documentation', // Custom site title
    }));
    
    // Serve Swagger JSON specification
    app.get('/api-docs.json', (req, res) => {
      // Return Swagger specification as JSON
      res.setHeader('Content-Type', 'application/json');
      res.send(swaggerSpec);
    });
  };

  // Export setup function
  module.exports = setupSwagger;
}
