package middleware

import (
	"context"
	"eslogad-be/internal/appcontext"
	"eslogad-be/internal/constants"
	"github.com/gin-gonic/gin"
)

func PopulateContext() gin.HandlerFunc {
	return func(c *gin.Context) {
		setKeyInContext(c, appcontext.AppIDKey, getAppID(c))
		setKeyInContext(c, appcontext.AppVersionKey, getAppVersion(c))
		setKeyInContext(c, appcontext.AppTypeKey, getAppType(c))
		setKeyInContext(c, appcontext.OrganizationIDKey, getOrganizationID(c))
		setKeyInContext(c, appcontext.DepartmentIDKey, getDepartmentID(c))
		setKeyInContext(c, appcontext.DeviceOSKey, getDeviceOS(c))
		setKeyInContext(c, appcontext.PlatformKey, getDevicePlatform(c))
		setKeyInContext(c, appcontext.UserLocaleKey, getUserLocale(c))
		c.Next()
	}
}

func getAppID(c *gin.Context) string {
	return c.GetHeader(constants.XAppIDHeader)
}

func getAppType(c *gin.Context) string {
	return c.GetHeader(constants.XAppTypeHeader)
}

func getAppVersion(c *gin.Context) string {
	return c.GetHeader(constants.XAppVersionHeader)
}

func getOrganizationID(c *gin.Context) string {
	return c.GetHeader(constants.OrganizationID)
}

func getDepartmentID(c *gin.Context) string {
	return c.GetHeader(constants.DepartmentID)
}

func getDeviceOS(c *gin.Context) string {
	return c.GetHeader(constants.XDeviceOSHeader)
}

func getDevicePlatform(c *gin.Context) string {
	return c.GetHeader(constants.XPlatformHeader)
}

func getUserLocale(c *gin.Context) string {
	userLocale := c.GetHeader(constants.XUserLocaleHeader)
	if userLocale == "" {
		userLocale = c.GetHeader(constants.AcceptedLanguageHeader)
	}
	if userLocale == "" {
		userLocale = c.GetHeader(constants.LocaleHeader)
	}
	return userLocale
}

func setKeyInContext(c *gin.Context, contextKey interface{}, contextKeyValue string) {
	ctx := context.WithValue(c.Request.Context(),
		contextKey, contextKeyValue)
	c.Request = c.Request.WithContext(ctx)
}
