package User

import (
	config "astrology-api/configs"
	dto "astrology-api/dto"
	repositories "astrology-api/repositories"
	services "astrology-api/services"

	"net/http"

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

type ReportController struct {
	chatHistoryService services.ChatHistoryService
	callHistoryService services.CallHistoryService
}

func NewReportController() *ReportController {

	db := config.DB

	chatRepo := repositories.NewChatHistoryRepository(db)
	callRepo := repositories.NewCallHistoryRepository(db)

	return &ReportController{
		chatHistoryService: services.NewChatHistoryService(chatRepo),
		callHistoryService: services.NewCallHistoryService(callRepo),
	}
}

//
// Get Chat History
//
func (rc *ReportController) GetChatHistory(c *gin.Context) {

	var req dto.GetChatHistoryRequest

	if err := c.ShouldBindJSON(&req); err != nil {

		c.JSON(http.StatusBadRequest, gin.H{
			"message": err.Error(),
			"status":  400,
		})
		return
	}

	userIDValue, exists := c.Get("user_id")
	if !exists {

		c.JSON(http.StatusUnauthorized, gin.H{
			"message": "Unauthorized",
			"status":  401,
		})
		return
	}

	userID := userIDValue.(uint)

	response, err := rc.chatHistoryService.GetChatHistory(
		userID,
		&req,
	)

	if err != nil {

		c.JSON(http.StatusInternalServerError, gin.H{
			"message": err.Error(),
			"status":  500,
		})
		return
	}

	if response.RecordList == nil {
		response.RecordList = []dto.ChatHistoryResponse{}
	}

	c.JSON(http.StatusOK, response)
}

func (rc *ReportController) GetCallHistory(c *gin.Context) {

	var req dto.GetCallHistoryRequest

	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"message": err.Error(),
			"status": 400,
		})
		return
	}

	userIDValue, exists := c.Get("user_id")
	if !exists {

		c.JSON(http.StatusUnauthorized, gin.H{
			"message": "Unauthorized",
			"status": 401,
		})
		return
	}

	userID := userIDValue.(uint)

	response, err := rc.callHistoryService.GetCallHistory(
		userID,
		&req,
	)

	if err != nil {

		c.JSON(http.StatusInternalServerError, gin.H{
			"message": err.Error(),
			"status": 500,
		})
		return
	}

	if response.RecordList == nil {
		response.RecordList = []dto.CallHistoryResponse{}
	}

	c.JSON(http.StatusOK, response)
}