package middleware

import (
	"apskel-pos-be/internal/logger"
	"apskel-pos-be/internal/models"
	"github.com/gin-gonic/gin"
	"github.com/google/uuid"
)

type UserIDResolver struct {
	userProcessor UserProcessor
	authProcessor AuthProcessor
}

func NewUserIDResolver(userProcessor UserProcessor, authProcessor AuthProcessor) *UserIDResolver {
	return &UserIDResolver{
		userProcessor: userProcessor,
		authProcessor: authProcessor,
	}
}

func (uir *UserIDResolver) Handle() gin.HandlerFunc {
	return func(c *gin.Context) {
		//tokenString := c.GetHeader("Authorization")
		//if tokenString == "" {
		//	c.JSON(http.StatusUnauthorized, gin.H{"error": "Authorization header is required"})
		//	c.Abort()
		//	return
		//}
		//
		//ctx := c.Request.Context()
		//
		//user, err := uir.resolveUserID(c, gopayAccountID)
		//if userID == "" {
		//	logger.FromContext(c.Request.Context()).Error("UserIDResolver::Handle -> userID could not be resolved")
		//	errorResponse := contract.BuildErrorResponse([]*contract.ResponseError{
		//		contract.NewResponseError(constants.InternalServerErrorCode, "user-id", "failed to resolve user id from gopay account id"),
		//	})
		//	util.WriteResponse(c.Writer, c.Request, *errorResponse, http.StatusInternalServerError, "UserIDResolver::Handle")
		//	c.Abort()
		//	return
		//}
		//
		//setKeyInContext(c, appcontext.UserIDKey, user.ID.String())
		//setKeyInContext(c, appcontext.OrganizationIDKey, user.OrganizationID.String())
		//setKeyInContext(c, appcontext.OutletIDKey, user.OutletID.String())
		//setKeyInContext(c, appcontext.RoleIDKey, string(user.Role))

		c.Next()
	}
}

func (uir *UserIDResolver) resolveUserID(c *gin.Context, userID uuid.UUID) (*models.UserResponse, error) {
	user, err := uir.userProcessor.GetUserByID(c.Request.Context(), userID)
	if err != nil {
		logger.FromContext(c.Request.Context()).WithError(err).Error("UserIDResolver::resolveGopayUserID -> userID could not be resolved")
		return nil, err
	}
	return user, nil
}

func (uir *UserIDResolver) validate(c *gin.Context, tokenString string) string {
	return ""
}
