package de.oaa.xxx.social;

import de.oaa.xxx.user.UserRepository;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.security.Principal;

@RestController
@RequestMapping("/events")
public class EventController {

    private final SseService sseService;
    private final UserRepository userRepository;

    public EventController(SseService sseService, UserRepository userRepository) {
        this.sseService     = sseService;
        this.userRepository = userRepository;
    }

    @GetMapping(path = "/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public SseEmitter stream(Principal principal) {
        var meOpt = userRepository.findByEmail(principal.getName());
        if (meOpt.isEmpty()) throw new RuntimeException("Not authenticated");
        return sseService.subscribe(meOpt.get().getUserId());
    }
}
