package pl.polskalokalnie.message;

import jakarta.validation.Valid;
import java.util.List;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ResponseStatusException;
import pl.polskalokalnie.user.AppUser;
import pl.polskalokalnie.user.UserRepository;

@RestController
@RequestMapping("/api/messages")
public class MessageController {

    private final MessageService messageService;
    private final UserRepository userRepository;

    public MessageController(MessageService messageService, UserRepository userRepository) {
        this.messageService = messageService;
        this.userRepository = userRepository;
    }

    @GetMapping("/admin")
    public List<MessageResponse> conversationWithAdmin(Authentication authentication) {
        AppUser me = currentUser(authentication);
        AppUser admin = messageService.resolveAdmin();
        return messageService.getConversation(me.getId(), admin.getId());
    }

    @PostMapping("/admin")
    public MessageResponse sendToAdmin(Authentication authentication, @Valid @RequestBody SendMessageRequest request) {
        AppUser me = currentUser(authentication);
        AppUser admin = messageService.resolveAdmin();
        return messageService.send(me.getId(), admin.getId(), request.content());
    }

    @GetMapping("/unread-count")
    public UnreadCountResponse unreadCount(Authentication authentication) {
        AppUser me = currentUser(authentication);
        AppUser admin = messageService.resolveAdmin();
        return new UnreadCountResponse(messageService.countUnreadFrom(me.getId(), admin.getId()));
    }

    private AppUser currentUser(Authentication authentication) {
        return userRepository.findByEmailIgnoreCase(authentication.getName())
                .orElseThrow(() -> new ResponseStatusException(HttpStatus.UNAUTHORIZED));
    }
}
