package com.iqser.red.service.persistence.management.v1.processor.service;

import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Service;

import com.iqser.red.service.persistence.management.v1.processor.service.persistence.NotificationPreferencesPersistenceService;
import com.iqser.red.service.persistence.service.v1.api.shared.model.notification.NotificationPreferences;

import lombok.AccessLevel;
import lombok.RequiredArgsConstructor;
import lombok.experimental.FieldDefaults;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
@RequiredArgsConstructor
@FieldDefaults(makeFinal = true, level = AccessLevel.PRIVATE)
public class NotificationPreferencesService {

    NotificationPreferencesPersistenceService notificationPreferencesPersistenceService;


    public NotificationPreferences getOrCreateNotificationPreferences(String userId) {

        var notificationPreferences = notificationPreferencesPersistenceService.getByUserId(userId);

        if (notificationPreferences != null) {
            return notificationPreferences;
        }

        try {
            notificationPreferencesPersistenceService.createNotificationPreferences(userId);
        } catch (DataIntegrityViolationException ex) {
            log.debug("NotificationPreferences might be already created by another Thread, ignoring...", ex);
        }

        return notificationPreferencesPersistenceService.getByUserId(userId);
    }

}
