const { logger } = require('../../middleware/logger');

class UserSettingsRepository {
  constructor(unitOfWork) {
    this.unitOfWork = unitOfWork;
  }

  async getSettingsByUserId(userId, unitOfWork = null) {
    logger.info('UserSettingsRepository.getSettingsByUserId:start', { userId });
    try {
      const conn = unitOfWork ? unitOfWork.connection : this.unitOfWork.connection;
      const [rows] = await conn.query('SELECT * FROM user_settings WHERE user_id = ?', [userId]);
      logger.info('UserSettingsRepository.getSettingsByUserId:success', { userId, found: rows.length > 0 });
      return rows.length > 0 ? rows[0] : null;
    } catch (error) {
      logger.error('UserSettingsRepository.getSettingsByUserId:error', { userId, error: error.message });
      throw error;
    }
  }

  async createDefaultSettings(userId, unitOfWork) {
    logger.info('UserSettingsRepository.createDefaultSettings:start', { userId });
    try {
      const conn = unitOfWork ? unitOfWork.connection : this.unitOfWork.connection;
      await conn.query(
        `INSERT INTO user_settings (user_id) VALUES (?) ON DUPLICATE KEY UPDATE user_id = user_id`,
        [userId]
      );
      logger.info('UserSettingsRepository.createDefaultSettings:success', { userId });
    } catch (error) {
      logger.error('UserSettingsRepository.createDefaultSettings:error', { userId, error: error.message });
      throw error;
    }
  }

  async updatePreferredLanguage(userId, preferredLanguage, unitOfWork = null) {
    logger.info('UserSettingsRepository.updatePreferredLanguage:start', { userId, preferredLanguage });
    try {
      const conn = unitOfWork ? unitOfWork.connection : this.unitOfWork.connection;
      await conn.query(
        `INSERT INTO user_settings (user_id, preferred_language)
         VALUES (?, ?)
         ON DUPLICATE KEY UPDATE preferred_language = VALUES(preferred_language)` ,
        [userId, preferredLanguage || null]
      );
      const settings = await this.getSettingsByUserId(userId, unitOfWork);
      logger.info('UserSettingsRepository.updatePreferredLanguage:success', {
        userId,
        preferredLanguage: settings?.preferred_language || null,
      });
      return settings;
    } catch (error) {
      logger.error('UserSettingsRepository.updatePreferredLanguage:error', {
        userId,
        preferredLanguage,
        error: error.message,
      });
      throw error;
    }
  }
}

module.exports = UserSettingsRepository;
