const TranslationService = require('../services/translationService');
const logger = require('../config/logger');

/**
 * Admin Translation Controller
 * Handles translation management endpoints
 */

/**
 * Get all translations with filtering
 * GET /api/v1/admin/translations
 */
const getTranslations = async (req, res) => {
  try {
    const { category, language, search, page = 1, limit = 20 } = req.query;

    const result = await TranslationService.getTranslations({
      category,
      language,
      search,
      page: parseInt(page),
      limit: parseInt(limit),
    });

    res.json({
      success: true,
      data: result.data,
      pagination: result.pagination,
    });
  } catch (error) {
    logger.error('Error in getTranslations:', error);
    res.status(error.statusCode || 500).json({
      success: false,
      error: {
        code: error.code || 'SERVER_ERROR',
        message: error.message || 'Failed to fetch translations',
      },
    });
  }
};

/**
 * Get translations by key (all languages)
 * GET /api/v1/admin/translations/:key
 */
const getTranslationsByKey = async (req, res) => {
  try {
    const { key } = req.params;

    const translations = await TranslationService.getTranslationsByKey(key);

    if (translations.length === 0) {
      return res.status(404).json({
        success: false,
        error: {
          code: 'TRANSLATION_NOT_FOUND',
          message: 'No translations found for this key',
        },
      });
    }

    // Format as object with language keys
    const formatted = {};
    translations.forEach(t => {
      formatted[t.language] = {
        id: t.id,
        value: t.value,
        category: t.category,
        description: t.description,
      };
    });

    res.json({
      success: true,
      data: {
        key,
        translations: formatted,
      },
    });
  } catch (error) {
    logger.error('Error in getTranslationsByKey:', error);
    res.status(error.statusCode || 500).json({
      success: false,
      error: {
        code: error.code || 'SERVER_ERROR',
        message: error.message || 'Failed to fetch translations',
      },
    });
  }
};

/**
 * Create a new translation
 * POST /api/v1/admin/translations
 */
const createTranslation = async (req, res) => {
  try {
    const { key, category, language, value, description } = req.body;

    // Validate required fields
    if (!key || !language || !value) {
      return res.status(400).json({
        success: false,
        error: {
          code: 'VALIDATION_ERROR',
          message: 'Key, language, and value are required',
        },
      });
    }

    const translation = await TranslationService.createTranslation({
      key,
      category,
      language,
      value,
      description,
    });

    res.status(201).json({
      success: true,
      message: 'Translation created successfully',
      data: translation,
    });
  } catch (error) {
    logger.error('Error in createTranslation:', error);
    res.status(error.statusCode || 500).json({
      success: false,
      error: {
        code: error.code || 'SERVER_ERROR',
        message: error.message || 'Failed to create translation',
      },
    });
  }
};

/**
 * Create or update translations for a key in multiple languages
 * POST /api/v1/admin/translations/batch
 */
const upsertTranslations = async (req, res) => {
  try {
    const { key, category, translations, description } = req.body;

    // Validate required fields
    if (!key || !translations || typeof translations !== 'object') {
      return res.status(400).json({
        success: false,
        error: {
          code: 'VALIDATION_ERROR',
          message: 'Key and translations object are required',
        },
      });
    }

    const results = await TranslationService.upsertTranslations({
      key,
      category,
      translations,
      description,
    });

    res.json({
      success: true,
      message: 'Translations saved successfully',
      data: {
        key,
        updated: results.length,
      },
    });
  } catch (error) {
    logger.error('Error in upsertTranslations:', error);
    res.status(error.statusCode || 500).json({
      success: false,
      error: {
        code: error.code || 'SERVER_ERROR',
        message: error.message || 'Failed to save translations',
      },
    });
  }
};

/**
 * Update a translation
 * PUT /api/v1/admin/translations/:id
 */
const updateTranslation = async (req, res) => {
  try {
    const { id } = req.params;
    const { value, category, description } = req.body;

    if (!value && !category && !description) {
      return res.status(400).json({
        success: false,
        error: {
          code: 'VALIDATION_ERROR',
          message: 'At least one field (value, category, description) is required',
        },
      });
    }

    const translation = await TranslationService.updateTranslation(id, {
      value,
      category,
      description,
    });

    res.json({
      success: true,
      message: 'Translation updated successfully',
      data: translation,
    });
  } catch (error) {
    logger.error('Error in updateTranslation:', error);
    res.status(error.statusCode || 500).json({
      success: false,
      error: {
        code: error.code || 'SERVER_ERROR',
        message: error.message || 'Failed to update translation',
      },
    });
  }
};

/**
 * Delete a translation
 * DELETE /api/v1/admin/translations/:id
 */
const deleteTranslation = async (req, res) => {
  try {
    const { id } = req.params;

    await TranslationService.deleteTranslation(id);

    res.json({
      success: true,
      message: 'Translation deleted successfully',
    });
  } catch (error) {
    logger.error('Error in deleteTranslation:', error);
    res.status(error.statusCode || 500).json({
      success: false,
      error: {
        code: error.code || 'SERVER_ERROR',
        message: error.message || 'Failed to delete translation',
      },
    });
  }
};

/**
 * Get all translation categories
 * GET /api/v1/admin/translations/categories
 */
const getCategories = async (req, res) => {
  try {
    const categories = await TranslationService.getCategories();

    res.json({
      success: true,
      data: categories,
    });
  } catch (error) {
    logger.error('Error in getCategories:', error);
    res.status(error.statusCode || 500).json({
      success: false,
      error: {
        code: error.code || 'SERVER_ERROR',
        message: error.message || 'Failed to fetch categories',
      },
    });
  }
};

module.exports = {
  getTranslations,
  getTranslationsByKey,
  createTranslation,
  upsertTranslations,
  updateTranslation,
  deleteTranslation,
  getCategories,
};
