package User

import (
	dto "astrology-api/dto/consultation"
	"astrology-api/middleware"
	services "astrology-api/services"
	"astrology-api/utils"
	"strconv"

	"github.com/gin-gonic/gin"
)

// The customer's side of the chat transcript.
//
// Agora RTM keeps no history, so the app buffers the conversation and posts it
// when the chat ends. Posting the same batch twice is safe, which is what
// makes blind retry the right client behaviour after a failed upload.
type ConsultationMessageController struct {
	messageService services.ConsultationMessageService
}

func NewConsultationMessageController(
	messageService services.ConsultationMessageService,
) *ConsultationMessageController {

	return &ConsultationMessageController{messageService: messageService}
}

// SyncMessages stores a batch of the transcript.
//
// POST /api/user/consultation/messages/sync
func (c *ConsultationMessageController) SyncMessages(ctx *gin.Context) {

	userID := middleware.GetUserID(ctx)

	if userID == 0 {
		utils.Unauthorized(ctx, "Unauthorized")
		return
	}

	var request dto.SyncMessagesRequest

	if err := ctx.ShouldBindJSON(&request); err != nil {
		utils.BadRequest(ctx, err.Error())
		return
	}

	response, err := c.messageService.SyncMessages(userID, request)

	if err != nil {
		utils.BadRequest(ctx, err.Error())
		return
	}

	utils.Success(ctx, "Transcript synced", response)
}

// GetMessages reads a stored transcript back.
//
// GET /api/user/consultation/messages?consultation_id=&page=&limit=
func (c *ConsultationMessageController) GetMessages(ctx *gin.Context) {

	userID := middleware.GetUserID(ctx)

	if userID == 0 {
		utils.Unauthorized(ctx, "Unauthorized")
		return
	}

	consultationID, _ := strconv.ParseUint(ctx.Query("consultation_id"), 10, 64)

	if consultationID == 0 {
		utils.BadRequest(ctx, "consultation_id is required")
		return
	}

	page, _ := strconv.Atoi(ctx.DefaultQuery("page", "1"))
	limit, _ := strconv.Atoi(ctx.DefaultQuery("limit", "200"))

	response, err := c.messageService.ListMessages(userID, uint(consultationID), page, limit)

	if err != nil {
		utils.NotFound(ctx, err.Error())
		return
	}

	utils.Success(ctx, "Chat messages", response)
}
