package de.cannamanage.service.push;

import de.cannamanage.service.repository.DeviceTokenRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * Firebase Cloud Messaging push sender.
 * Sends push notifications to Android/iOS devices via FCM.
 * <p>
 * Gracefully degrades if Firebase credentials are not configured —
 * logs a warning on startup but doesn't fail.
 */
@Slf4j
@Service
public class FcmPushSender {

    @Value("${push.fcm.credentials-path:}")
    private String credentialsPath;

    private final DeviceTokenRepository deviceTokenRepository;
    private boolean initialized = false;

    public FcmPushSender(DeviceTokenRepository deviceTokenRepository) {
        this.deviceTokenRepository = deviceTokenRepository;
    }

    @jakarta.annotation.PostConstruct
    void init() {
        if (credentialsPath == null || credentialsPath.isBlank()) {
            log.warn("FCM credentials not configured — push notifications to mobile devices disabled");
            return;
        }

        try {
            // Firebase Admin SDK initialization would go here:
            // FirebaseOptions options = FirebaseOptions.builder()
            //     .setCredentials(GoogleCredentials.fromStream(new FileInputStream(credentialsPath)))
            //     .build();
            // FirebaseApp.initializeApp(options);
            // messaging = FirebaseMessaging.getInstance();

            // For MVP: mark as not initialized until firebase-admin is added to POM
            log.info("FCM credentials path configured: {} — SDK integration pending", credentialsPath);
            initialized = false;
        } catch (Exception e) {
            log.error("Failed to initialize FCM: {}", e.getMessage());
        }
    }

    /**
     * Send a push notification via FCM.
     * Handles expired tokens by removing them from the database.
     */
    public void send(String fcmToken, PushPayload payload) {
        if (!initialized) {
            log.debug("FCM not initialized — skipping push to token {}", 
                    fcmToken.length() > 10 ? fcmToken.substring(0, 10) + "..." : fcmToken);
            return;
        }

        // Firebase Admin SDK send logic:
        // Message message = Message.builder()
        //     .setToken(fcmToken)
        //     .setNotification(Notification.builder()
        //         .setTitle(payload.getTitle())
        //         .setBody(payload.getBody())
        //         .build())
        //     .putAllData(payload.getData() != null ? payload.getData() : Map.of())
        //     .build();
        //
        // try {
        //     messaging.send(message);
        // } catch (FirebaseMessagingException e) {
        //     if (e.getMessagingErrorCode() == MessagingErrorCode.UNREGISTERED) {
        //         deviceTokenRepository.deleteByToken(fcmToken);
        //         log.warn("Removed expired FCM token");
        //     }
        // }
    }

    public boolean isConfigured() {
        return initialized;
    }
}
