const configService = require('../services/configService');
const { sendSuccess, sendError } = require('../utils/response');

/**
 * Admin Config Controller
 * Handles admin configuration management
 */

/**
 * Get all configurations
 * GET /api/v1/admin/config
 */
const getAllConfigs = async (req, res) => {
  try {
    const { category } = req.query;
    const configs = await configService.getAllConfigs(category);
    return sendSuccess(res, configs, 'Configurations retrieved successfully');
  } catch (error) {
    console.error('Get all configs error:', error);
    return sendError(res, error.message || 'Failed to get configurations', 500, 500);
  }
};

/**
 * Get configuration by key
 * GET /api/v1/admin/config/:key
 */
const getConfig = async (req, res) => {
  try {
    const { key } = req.params;
    const config = await configService.getConfig(key);
    
    if (!config) {
      return sendError(res, 'Configuration not found', 404, 404);
    }
    
    return sendSuccess(res, config, 'Configuration retrieved successfully');
  } catch (error) {
    console.error('Get config error:', error);
    return sendError(res, error.message || 'Failed to get configuration', 500, 500);
  }
};

/**
 * Update configuration
 * PUT /api/v1/admin/config/:key
 */
const updateConfig = async (req, res) => {
  try {
    const { key } = req.params;
    const { value, type, category, description } = req.body;
    
    const config = await configService.setConfig(key, value, type, category, description);
    
    return sendSuccess(res, config, 'Configuration updated successfully');
  } catch (error) {
    console.error('Update config error:', error);
    return sendError(res, error.message || 'Failed to update configuration', 500, 500);
  }
};

/**
 * Delete configuration
 * DELETE /api/v1/admin/config/:key
 */
const deleteConfig = async (req, res) => {
  try {
    const { key } = req.params;
    const deleted = await configService.deleteConfig(key);
    
    if (!deleted) {
      return sendError(res, 'Configuration not found', 404, 404);
    }
    
    return sendSuccess(res, null, 'Configuration deleted successfully');
  } catch (error) {
    console.error('Delete config error:', error);
    return sendError(res, error.message || 'Failed to delete configuration', 500, 500);
  }
};

module.exports = {
  getAllConfigs,
  getConfig,
  updateConfig,
  deleteConfig,
};
