package com.smyhub.store.mengyastorebackendjava.controller;

import com.smyhub.store.mengyastorebackendjava.dto.request.ChatMessageRequest;
import com.smyhub.store.mengyastorebackendjava.dto.response.ApiResponse;
import com.smyhub.store.mengyastorebackendjava.dto.response.ChatMessageResponse;
import com.smyhub.store.mengyastorebackendjava.security.CurrentUserHolder;
import com.smyhub.store.mengyastorebackendjava.security.SproutGateUser;
import com.smyhub.store.mengyastorebackendjava.service.ChatService;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/chat")
@RequiredArgsConstructor
public class ChatController {

    private final ChatService chatService;

    @GetMapping("/messages")
    public ResponseEntity<ApiResponse<List<ChatMessageResponse>>> getMessages() {
        String account = CurrentUserHolder.get().getAccount();
        return ResponseEntity.ok(ApiResponse.ok(chatService.getUserMessages(account)));
    }

    @PostMapping("/messages")
    public ResponseEntity<ApiResponse<ChatMessageResponse>> sendMessage(
            @Valid @RequestBody ChatMessageRequest req) {
        SproutGateUser user = CurrentUserHolder.get();
        ChatMessageResponse msg = chatService.sendUserMessage(
                user.getAccount(), user.getUsername(), req.getContent()
        );
        return ResponseEntity.ok(ApiResponse.ok(msg));
    }
}
