const UnitOfWork = require('../../database/UnitOfWork');
const UserSettingsRepository = require('../../repositories/settings/UserSettingsRepository');
const I18nPreferencesRepository = require('../../repositories/settings/I18nPreferencesRepository');
const { logger } = require('../../middleware/logger'); // <-- import logger
const { normalizeLanguageCode } = require('../../utils/languageUtils');

const i18nPreferencesRepository = new I18nPreferencesRepository();

async function resolvePreferredLanguage(rawValue) {
  if (rawValue === undefined) return undefined;
  if (rawValue === null || String(rawValue).trim() === '') return null;

  const normalized = normalizeLanguageCode(rawValue);
  if (!normalized) return '';

  const languages = await i18nPreferencesRepository.listLanguages({ enabledOnly: true });
  return languages.some((entry) => entry.languageCode === normalized) ? normalized : '';
}

class UserSettingsController {
  static async getSettings(req, res) {
    const userId = req.user.userId;
    logger.info(`[UserSettingsController] getSettings called for userId: ${userId}`);
    const unitOfWork = new UnitOfWork();
    await unitOfWork.start();
    try {
      const repo = new UserSettingsRepository(unitOfWork);
      const settings = await repo.getSettingsByUserId(userId);
      await unitOfWork.commit();
      if (!settings) {
        logger.warn(`[UserSettingsController] No settings found for userId: ${userId}`);
        return res.status(404).json({ success: false, message: 'Settings not found' });
      }
      logger.info(`[UserSettingsController] getSettings success for userId: ${userId}`);
      res.json({ success: true, settings });
    } catch (error) {
      logger.error(`[UserSettingsController] getSettings error for userId: ${userId}`, { error });
      await unitOfWork.rollback(error);
      res.status(500).json({ success: false, message: error.message });
    }
  }

  static async updateSettings(req, res) {
    const userId = req.user.userId;
    logger.info(`[UserSettingsController] updateSettings called for userId: ${userId}`);

    const rawPreferredLanguage = req.body?.preferredLanguage
      ?? req.body?.preferred_language
      ?? req.body?.language
      ?? req.body?.lang;

    if (rawPreferredLanguage === undefined) {
      return res.status(400).json({
        success: false,
        message: 'No supported settings payload provided',
      });
    }

    const preferredLanguage = await resolvePreferredLanguage(rawPreferredLanguage);
    if (preferredLanguage === '') {
      return res.status(400).json({
        success: false,
        message: 'Invalid preferred language',
      });
    }

    const unitOfWork = new UnitOfWork();
    await unitOfWork.start();
    try {
      const repo = new UserSettingsRepository(unitOfWork);
      const settings = await repo.updatePreferredLanguage(userId, preferredLanguage, unitOfWork);
      await unitOfWork.commit();
      logger.info(`[UserSettingsController] updateSettings success for userId: ${userId}`, {
        preferredLanguage: settings?.preferred_language || null,
      });
      return res.json({ success: true, settings });
    } catch (error) {
      logger.error(`[UserSettingsController] updateSettings error for userId: ${userId}`, { error });
      await unitOfWork.rollback(error);
      return res.status(500).json({ success: false, message: error.message });
    }
  }
}

module.exports = UserSettingsController;
