const { validationResult } = require('express-validator');
const ServiceService = require('../services/serviceService');
const logger = require('../config/logger');

/**
 * Service Controller
 * Handles service and category API endpoints
 */
class ServiceController {
  /**
   * Get all categories
   * @route GET /api/v1/categories
   */
  static async getCategories(req, res, next) {
    try {
      const language = req.user?.language || req.query.language || 'zh';

      const categories = await ServiceService.getCategories(language);

      res.json({
        success: true,
        data: categories,
      });
    } catch (error) {
      logger.error('Error in getCategories:', error);
      next(error);
    }
  }

  /**
   * Get services with pagination and filtering
   * @route GET /api/v1/services
   */
  static async getServices(req, res, next) {
    try {
      const errors = validationResult(req);
      if (!errors.isEmpty()) {
        return res.status(400).json({
          success: false,
          error: {
            code: 'VALIDATION_ERROR',
            message: 'Invalid request parameters',
            details: errors.array(),
          },
        });
      }

      const { page = 1, limit = 10, categoryKey } = req.query;
      const language = req.user?.language || req.query.language || 'zh';

      const result = await ServiceService.getServices({
        page: parseInt(page),
        limit: parseInt(limit),
        categoryKey,
        language,
      });

      res.json({
        success: true,
        data: result.data,
        pagination: result.pagination,
      });
    } catch (error) {
      logger.error('Error in getServices:', error);
      next(error);
    }
  }

  /**
   * Get service by key
   * @route GET /api/v1/services/:key
   */
  static async getServiceByKey(req, res, next) {
    try {
      const { key } = req.params;
      const language = req.user?.language || req.query.language || 'zh';

      const service = await ServiceService.getServiceByKey(key, language);

      if (!service) {
        return res.status(404).json({
          success: false,
          error: {
            code: 'SERVICE_NOT_FOUND',
            message: 'Service not found',
          },
        });
      }

      res.json({
        success: true,
        data: service,
      });
    } catch (error) {
      logger.error('Error in getServiceByKey:', error);
      next(error);
    }
  }
}

module.exports = ServiceController;
