package dev.ksan.etfoglasiserver.service;

import dev.ksan.etfoglasiserver.model.DeviceToken;
import dev.ksan.etfoglasiserver.model.User;
import dev.ksan.etfoglasiserver.repository.DeviceTokenRepo;
import dev.ksan.etfoglasiserver.repository.UserRepo;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
public class DeviceTokenService {

    private final DeviceTokenRepo deviceTokenRepo;
    private final UserRepo userRepo;

    public void registerToken(String email, String token) {

        User user = userRepo.findByEmail(email)
                .orElseThrow(() -> new RuntimeException("User not found"));

        DeviceToken deviceToken = deviceTokenRepo
                .findByFcmToken(token)
                .orElse(new DeviceToken());

        deviceToken.setUser(user);
        deviceToken.setFcmToken(token);

        deviceTokenRepo.save(deviceToken);
    }
}