package dev.ksan.etfoglasiserver.service;

import com.google.firebase.messaging.*;
import dev.ksan.etfoglasiserver.model.DeviceToken;
import dev.ksan.etfoglasiserver.model.User;
import dev.ksan.etfoglasiserver.repository.DeviceTokenRepo;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@RequiredArgsConstructor
public class NotificationService {

    private final DeviceTokenRepo deviceTokenRepo;
    private final FirebaseMessaging firebaseMessaging;

    public void sendToUser(User user, String title, String body)
            throws FirebaseMessagingException {

        List<DeviceToken> tokens =
                deviceTokenRepo.findByUserId(user.getId());

        for (DeviceToken token : tokens) {

            // Include a notification block so Android's system tray displays it
            // even when the app is killed/dozing (a data-only message is only
            // ever shown by the app's own JS handler, which won't run when the
            // OS has force-stopped the app). HIGH priority tells FCM to deliver
            // promptly and wake the device out of Doze.
            Message message = Message.builder()
                    .setToken(token.getFcmToken())
                    .setNotification(Notification.builder()
                            .setTitle(title)
                            .setBody(body)
                            .build())
                    .setAndroidConfig(AndroidConfig.builder()
                            .setPriority(AndroidConfig.Priority.HIGH)
                            .build())
                    .putData("title", title)
                    .putData("body", body)
                    .build();

            try {
                String id = firebaseMessaging.send(message);
                System.out.println("Send:" + id);
            } catch (FirebaseMessagingException ex) {

                ex.printStackTrace();
                if (ex.getMessagingErrorCode()
                        == MessagingErrorCode.UNREGISTERED) {
                    deviceTokenRepo.delete(token);
                }
            }
        }
    }
}