package Astrologer

import (
	dto "astrology-api/dto/consultation"
	"astrology-api/helpers"
	"astrology-api/services"
	"net/http"
	"strconv"

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

// The astrologer's side of the chat transcript.
//
// Both apps upload the same conversation, and that is deliberate: each device
// holds all of it, but only one may survive being killed. The unique key on
// (consultationId, clientMessageId) means the second copy costs nothing, so
// the redundancy is free and the transcript survives one phone dying.
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/astrologer/consultation/messages/sync
func (c *ConsultationMessageController) SyncMessages(ctx *gin.Context) {

	userID := ctx.MustGet("user_id").(uint)

	var request dto.SyncMessagesRequest

	if err := ctx.ShouldBindJSON(&request); err != nil {
		ctx.JSON(http.StatusBadRequest, helpers.ErrorResponse(err.Error()))
		return
	}

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

	if err != nil {
		ctx.JSON(http.StatusBadRequest, helpers.ErrorResponse(err.Error()))
		return
	}

	ctx.JSON(http.StatusOK, helpers.SuccessResponse("Transcript synced", response))
}

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

	userID := ctx.MustGet("user_id").(uint)

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

	if consultationID == 0 {
		ctx.JSON(http.StatusBadRequest, helpers.ErrorResponse("consultation_id is required"))
		return
	}

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

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

	if err != nil {
		ctx.JSON(http.StatusBadRequest, helpers.ErrorResponse(err.Error()))
		return
	}

	ctx.JSON(http.StatusOK, helpers.SuccessResponse("Chat messages", response))
}
