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

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

  async getSettingsByUserId(userId) {
    logger.info('UserSettingsRepository.getSettingsByUserId:start', { userId });
    try {
      const conn = 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;
    }
  }
}

module.exports = UserSettingsRepository;
