package handler

import (
	"bpmsapi/entity"
	"bpmsapi/repository"
	"bpmsapi/service"
	"bpmsapi/util"

	"io"
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
)

type QuotationHandler struct {
	logName string
}

func NewQuotationHandler(logName string) *QuotationHandler {
	return &QuotationHandler{
		logName: logName,
	}
}

func (quotationHandler *QuotationHandler) UpdateQuotationDetailsHandler(c *gin.Context) {

	var response entity.CustomResponse
	db, err := util.GetDBConnection()

	if db != nil {
		defer db.Close()
	}

	if err != nil {
		response.Message = "Problem in Database connection. Please try again"
		response.Resultcode = 1
		c.Set("response", response)
		return
	}

	body := entity.UpdateQuotationDetailsInput{}
	if err := c.ShouldBindJSON(&body); err != nil && err != io.EOF {
		switch err.(type) {
		case validator.ValidationErrors:
			c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{
				"error": err.(validator.ValidationErrors).Translate(util.Trans),
			})
		default:
			c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{
				"error": err.Error()})

		}

		return
	} else {
		if err != nil && err == io.EOF {
			if util.CheckRequired(body) {
				c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "Mandatory input fields missing"})
				return
			}
		}
	}

	body = util.Default_tag(body).(entity.UpdateQuotationDetailsInput)

	quotationRepository := repository.QuotationRepositoryInit(db)
	quotationService := service.QuotationServiceInit(quotationRepository)
	response = quotationService.UpdateQuotationDetails(body)
	c.Set("response", response)

}
