package de.cannamanage.service;

import de.cannamanage.domain.entity.NotificationPreference;
import de.cannamanage.domain.enums.NotificationChannel;
import de.cannamanage.service.repository.NotificationPreferenceRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.UUID;

/**
 * Central dispatch service that fans out notifications to all enabled channels per user.
 * Channels: IN_APP (always on), EMAIL (opt-in), WEB_PUSH (opt-in), MOBILE_PUSH (opt-in).
 * 
 * Called by NotificationService after creating the in-app notification record.
 */
@Slf4j
@Service
public class NotificationDispatchService {

    private final NotificationPreferenceRepository preferenceRepository;
    private final EmailService emailService;

    public NotificationDispatchService(NotificationPreferenceRepository preferenceRepository,
                                       EmailService emailService) {
        this.preferenceRepository = preferenceRepository;
        this.emailService = emailService;
    }

    /**
     * Dispatch a notification to all enabled channels for a single user.
     * IN_APP is already handled by the caller (NotificationService creates the DB record + WebSocket push).
     * This method handles EMAIL channel.
     * 
     * @param userEmail the user's email (null if not available)
     * @param userName the user's display name
     */
    @Async
    public void dispatchToUser(UUID userId, String userEmail, String userName,
                               String title, String message, String actionLink) {
        if (userEmail == null || userEmail.isBlank()) {
            log.debug("No email for user {}, skipping email dispatch", userId);
            return;
        }

        try {
            // Check if user has EMAIL channel enabled
            boolean emailEnabled = preferenceRepository
                    .findByUserIdAndChannel(userId, NotificationChannel.EMAIL)
                    .map(NotificationPreference::isEnabled)
                    .orElse(false); // Default: email is opt-in, so disabled if no preference exists

            if (emailEnabled) {
                emailService.sendNotificationEmail(userEmail, userName, title, message, actionLink);
                log.debug("Email dispatched to {} for notification: {}", userEmail, title);
            }
        } catch (Exception e) {
            log.warn("Failed to dispatch email to user {}: {}", userId, e.getMessage());
        }

        // Web Push and Mobile Push would be dispatched here in future
    }

    /**
     * Dispatch method called by NotificationService after saving a notification.
     * Fans out to email/push channels based on user preferences.
     */
    @Async
    public void dispatch(de.cannamanage.domain.entity.Notification notification, UUID userId) {
        // For now, this is a no-op placeholder for push channels.
        // Email dispatch requires user email which is not on the Notification entity.
        // Full email integration will be triggered explicitly via dispatchToUser() when email is known.
        log.debug("Dispatch hook called for notification {} to user {}", notification.getId(), userId);
    }

    /**
     * Check if a user has email notifications enabled.
     */
    public boolean isEmailEnabled(UUID userId) {
        return preferenceRepository
                .findByUserIdAndChannel(userId, NotificationChannel.EMAIL)
                .map(NotificationPreference::isEnabled)
                .orElse(false);
    }
}
