package handler

import (
	"apskel-pos-be/internal/appcontext"
	"apskel-pos-be/internal/util"
	"strconv"

	"apskel-pos-be/internal/constants"
	"apskel-pos-be/internal/contract"
	"apskel-pos-be/internal/logger"
	"apskel-pos-be/internal/service"
	"apskel-pos-be/internal/validator"

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

type VendorHandler struct {
	vendorService   service.VendorService
	vendorValidator validator.VendorValidator
}

func NewVendorHandler(
	vendorService service.VendorService,
	vendorValidator validator.VendorValidator,
) *VendorHandler {
	return &VendorHandler{
		vendorService:   vendorService,
		vendorValidator: vendorValidator,
	}
}

func (h *VendorHandler) CreateVendor(c *gin.Context) {
	ctx := c.Request.Context()
	contextInfo := appcontext.FromGinContext(ctx)

	var req contract.CreateVendorRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		logger.FromContext(c.Request.Context()).WithError(err).Error("VendorHandler::CreateVendor -> request binding failed")
		validationResponseError := contract.NewResponseError(constants.MissingFieldErrorCode, constants.RequestEntity, err.Error())
		util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{validationResponseError}), "VendorHandler::CreateVendor")
		return
	}

	validationError, validationErrorCode := h.vendorValidator.ValidateCreateVendorRequest(&req)
	if validationError != nil {
		validationResponseError := contract.NewResponseError(validationErrorCode, constants.RequestEntity, validationError.Error())
		util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{validationResponseError}), "VendorHandler::CreateVendor")
		return
	}

	vendorResponse := h.vendorService.CreateVendor(ctx, contextInfo, &req)
	if vendorResponse.HasErrors() {
		errorResp := vendorResponse.GetErrors()[0]
		logger.FromContext(ctx).WithError(errorResp).Error("VendorHandler::CreateVendor -> Failed to create vendor from service")
	}

	util.HandleResponse(c.Writer, c.Request, vendorResponse, "VendorHandler::CreateVendor")
}

func (h *VendorHandler) UpdateVendor(c *gin.Context) {
	ctx := c.Request.Context()
	contextInfo := appcontext.FromGinContext(ctx)

	vendorIDStr := c.Param("id")
	vendorID, err := uuid.Parse(vendorIDStr)
	if err != nil {
		logger.FromContext(ctx).WithError(err).Error("VendorHandler::UpdateVendor -> Invalid vendor ID")
		validationResponseError := contract.NewResponseError(constants.MalformedFieldErrorCode, constants.RequestEntity, "Invalid vendor ID")
		util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{validationResponseError}), "VendorHandler::UpdateVendor")
		return
	}

	var req contract.UpdateVendorRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		logger.FromContext(ctx).WithError(err).Error("VendorHandler::UpdateVendor -> request binding failed")
		validationResponseError := contract.NewResponseError(constants.MissingFieldErrorCode, constants.RequestEntity, "Invalid request body")
		util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{validationResponseError}), "VendorHandler::UpdateVendor")
		return
	}

	validationError, validationErrorCode := h.vendorValidator.ValidateUpdateVendorRequest(&req)
	if validationError != nil {
		validationResponseError := contract.NewResponseError(validationErrorCode, constants.RequestEntity, validationError.Error())
		util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{validationResponseError}), "VendorHandler::UpdateVendor")
		return
	}

	vendorResponse := h.vendorService.UpdateVendor(ctx, contextInfo, vendorID, &req)
	if vendorResponse.HasErrors() {
		errorResp := vendorResponse.GetErrors()[0]
		logger.FromContext(ctx).WithError(errorResp).Error("VendorHandler::UpdateVendor -> Failed to update vendor from service")
	}

	util.HandleResponse(c.Writer, c.Request, vendorResponse, "VendorHandler::UpdateVendor")
}

func (h *VendorHandler) DeleteVendor(c *gin.Context) {
	ctx := c.Request.Context()
	contextInfo := appcontext.FromGinContext(ctx)

	vendorIDStr := c.Param("id")
	vendorID, err := uuid.Parse(vendorIDStr)
	if err != nil {
		logger.FromContext(ctx).WithError(err).Error("VendorHandler::DeleteVendor -> Invalid vendor ID")
		validationResponseError := contract.NewResponseError(constants.MalformedFieldErrorCode, constants.RequestEntity, "Invalid vendor ID")
		util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{validationResponseError}), "VendorHandler::DeleteVendor")
		return
	}

	vendorResponse := h.vendorService.DeleteVendor(ctx, contextInfo, vendorID)
	if vendorResponse.HasErrors() {
		errorResp := vendorResponse.GetErrors()[0]
		logger.FromContext(ctx).WithError(errorResp).Error("VendorHandler::DeleteVendor -> Failed to delete vendor from service")
	}

	util.HandleResponse(c.Writer, c.Request, vendorResponse, "VendorHandler::DeleteVendor")
}

func (h *VendorHandler) GetVendor(c *gin.Context) {
	ctx := c.Request.Context()
	contextInfo := appcontext.FromGinContext(ctx)

	vendorIDStr := c.Param("id")
	vendorID, err := uuid.Parse(vendorIDStr)
	if err != nil {
		logger.FromContext(ctx).WithError(err).Error("VendorHandler::GetVendor -> Invalid vendor ID")
		validationResponseError := contract.NewResponseError(constants.MalformedFieldErrorCode, constants.RequestEntity, "Invalid vendor ID")
		util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{validationResponseError}), "VendorHandler::GetVendor")
		return
	}

	vendorResponse := h.vendorService.GetVendorByID(ctx, contextInfo, vendorID)
	if vendorResponse.HasErrors() {
		errorResp := vendorResponse.GetErrors()[0]
		logger.FromContext(ctx).WithError(errorResp).Error("VendorHandler::GetVendor -> Failed to get vendor from service")
	}

	util.HandleResponse(c.Writer, c.Request, vendorResponse, "VendorHandler::GetVendor")
}

func (h *VendorHandler) ListVendors(c *gin.Context) {
	ctx := c.Request.Context()
	contextInfo := appcontext.FromGinContext(ctx)

	req := &contract.ListVendorsRequest{
		Page:  1,
		Limit: 10,
	}

	// Parse query parameters
	if pageStr := c.Query("page"); pageStr != "" {
		if page, err := strconv.Atoi(pageStr); err == nil {
			req.Page = page
		}
	}

	if limitStr := c.Query("limit"); limitStr != "" {
		if limit, err := strconv.Atoi(limitStr); err == nil {
			req.Limit = limit
		}
	}

	if search := c.Query("search"); search != "" {
		req.Search = search
	}

	if isActiveStr := c.Query("is_active"); isActiveStr != "" {
		if isActive, err := strconv.ParseBool(isActiveStr); err == nil {
			req.IsActive = &isActive
		}
	}

	validationError, validationErrorCode := h.vendorValidator.ValidateListVendorsRequest(req)
	if validationError != nil {
		validationResponseError := contract.NewResponseError(validationErrorCode, constants.RequestEntity, validationError.Error())
		util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{validationResponseError}), "VendorHandler::ListVendors")
		return
	}

	vendorResponse := h.vendorService.ListVendors(ctx, contextInfo, req)
	if vendorResponse.HasErrors() {
		errorResp := vendorResponse.GetErrors()[0]
		logger.FromContext(ctx).WithError(errorResp).Error("VendorHandler::ListVendors -> Failed to list vendors from service")
	}

	util.HandleResponse(c.Writer, c.Request, vendorResponse, "VendorHandler::ListVendors")
}

func (h *VendorHandler) GetActiveVendors(c *gin.Context) {
	ctx := c.Request.Context()
	contextInfo := appcontext.FromGinContext(ctx)

	vendorResponse := h.vendorService.GetActiveVendors(ctx, contextInfo)
	if vendorResponse.HasErrors() {
		errorResp := vendorResponse.GetErrors()[0]
		logger.FromContext(ctx).WithError(errorResp).Error("VendorHandler::GetActiveVendors -> Failed to get active vendors from service")
	}

	util.HandleResponse(c.Writer, c.Request, vendorResponse, "VendorHandler::GetActiveVendors")
}
