package auth

import (
	"net/http"

	"github.com/gin-gonic/gin"

	"gitlab.com/dynaweb/ains-microservices/pkg/config"
)

const stateCookieName = "ains_oauth_state"

func accessCookieName(cfg *config.Config) string {
	return cfg.Auth.CookieName
}

func refreshCookieName(cfg *config.Config) string {
	return cfg.Auth.CookieName + "_refresh"
}

func SetAuthCookies(c *gin.Context, cfg *config.Config, access, refresh string) {
	secure := cfg.Auth.CookieSecure || cfg.App.IsProduction()
	domain := cfg.Auth.CookieDomain

	setCookie(c, accessCookieName(cfg), access, int(cfg.JWT.AccessTTL.Seconds()), domain, secure)
	setCookie(c, refreshCookieName(cfg), refresh, int(cfg.JWT.RefreshTTL.Seconds()), domain, secure)
}

func ClearAuthCookies(c *gin.Context, cfg *config.Config) {
	clearCookie(c, accessCookieName(cfg), cfg.Auth.CookieDomain)
	clearCookie(c, refreshCookieName(cfg), cfg.Auth.CookieDomain)
	clearCookie(c, stateCookieName, cfg.Auth.CookieDomain)
}

func setStateCookie(c *gin.Context, cfg *config.Config, state string) {
	setCookie(c, stateCookieName, state, 600, cfg.Auth.CookieDomain, cfg.Auth.CookieSecure)
}

func setCookie(c *gin.Context, name, value string, maxAge int, domain string, secure bool) {
	http.SetCookie(c.Writer, &http.Cookie{
		Name:     name,
		Value:    value,
		Path:     "/",
		Domain:   domain,
		MaxAge:   maxAge,
		Secure:   secure,
		HttpOnly: true,
		SameSite: http.SameSiteLaxMode,
	})
}

func clearCookie(c *gin.Context, name, domain string) {
	http.SetCookie(c.Writer, &http.Cookie{
		Name:     name,
		Value:    "",
		Path:     "/",
		Domain:   domain,
		MaxAge:   -1,
		HttpOnly: true,
		SameSite: http.SameSiteLaxMode,
	})
}
