package User

import (
	"net/http"

	dto "astrology-api/dto/astrology"
	"astrology-api/helpers"
	"astrology-api/services"

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

///////////////////////////////////////////////////////////
// Panchang Controller
///////////////////////////////////////////////////////////

type PanchangController struct {
	service services.PanchangService
}

func NewPanchangController(service services.PanchangService) *PanchangController {
	return &PanchangController{service: service}
}

///////////////////////////////////////////////////////////
// Shared Handler
///////////////////////////////////////////////////////////

// lookup handles the panchang endpoints, which all take the same request body.
func (c *PanchangController) lookup(
	ctx *gin.Context,
	call func(uint, dto.PanchangRequest) (*dto.VedicDataResponse, error),
	message string,
) {

	var request dto.PanchangRequest

	if err := ctx.ShouldBindJSON(&request); err != nil {

		ctx.JSON(http.StatusBadRequest, helpers.ErrorResponse(err.Error()))

		return
	}

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

	response, err := call(userID, request)

	if err != nil {

		ctx.JSON(http.StatusBadRequest, helpers.ErrorResponse(err.Error()))

		return
	}

	ctx.JSON(http.StatusOK, helpers.SuccessResponse(message, response))
}

func (c *PanchangController) Today(ctx *gin.Context) {
	c.lookup(ctx, c.service.Today, "Panchang fetched successfully.")
}

func (c *PanchangController) Monthly(ctx *gin.Context) {
	c.lookup(ctx, c.service.Monthly, "Monthly panchang fetched successfully.")
}

func (c *PanchangController) Choghadiya(ctx *gin.Context) {
	c.lookup(ctx, c.service.Choghadiya, "Choghadiya muhurta fetched successfully.")
}

func (c *PanchangController) Hora(ctx *gin.Context) {
	c.lookup(ctx, c.service.Hora, "Hora muhurta fetched successfully.")
}

func (c *PanchangController) Festivals(ctx *gin.Context) {
	c.lookup(ctx, c.service.Festivals, "Festivals fetched successfully.")
}

///////////////////////////////////////////////////////////
// Sun & Moon
///////////////////////////////////////////////////////////

func (c *PanchangController) SunMoon(ctx *gin.Context) {

	var request dto.PanchangRequest

	if err := ctx.ShouldBindJSON(&request); err != nil {

		ctx.JSON(http.StatusBadRequest, helpers.ErrorResponse(err.Error()))

		return
	}

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

	response, err := c.service.SunMoon(userID, request)

	if err != nil {

		ctx.JSON(http.StatusBadRequest, helpers.ErrorResponse(err.Error()))

		return
	}

	ctx.JSON(
		http.StatusOK,
		helpers.SuccessResponse("Sun and moon timings fetched successfully.", response),
	)
}
