package handlers

import (
	"net/http"

	"git.mchus.pro/mchus/quoteforge/internal/services"
	"github.com/gin-gonic/gin"
)

type QuoteHandler struct {
	quoteService *services.QuoteService
}

func NewQuoteHandler(quoteService *services.QuoteService) *QuoteHandler {
	return &QuoteHandler{quoteService: quoteService}
}

func (h *QuoteHandler) Validate(c *gin.Context) {
	var req services.QuoteRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		RespondError(c, http.StatusUnprocessableEntity, "invalid request", err)
		return
	}

	result, err := h.quoteService.ValidateAndCalculate(&req)
	if err != nil {
		RespondError(c, http.StatusUnprocessableEntity, "invalid request", err)
		return
	}

	c.JSON(http.StatusOK, result)
}

func (h *QuoteHandler) Calculate(c *gin.Context) {
	var req services.QuoteRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		RespondError(c, http.StatusUnprocessableEntity, "invalid request", err)
		return
	}

	result, err := h.quoteService.ValidateAndCalculate(&req)
	if err != nil {
		RespondError(c, http.StatusUnprocessableEntity, "invalid request", err)
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"items": result.Items,
		"total": result.Total,
	})
}

func (h *QuoteHandler) PriceLevels(c *gin.Context) {
	var req services.PriceLevelsRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		RespondError(c, http.StatusUnprocessableEntity, "invalid request", err)
		return
	}

	result, err := h.quoteService.CalculatePriceLevels(&req)
	if err != nil {
		RespondError(c, http.StatusUnprocessableEntity, "invalid request", err)
		return
	}

	c.JSON(http.StatusOK, result)
}
