package oauth

import (
	"encoding/base64"
	"net/http"

	"github.com/pkg/errors"
)

func SetStateCookie(w http.ResponseWriter, uak []byte, ssl bool) {
	encodedUak := base64.RawURLEncoding.EncodeToString(uak)
	http.SetCookie(w, &http.Cookie{
		Name:     "oauth_uak",
		Value:    encodedUak,
		Path:     "/",
		MaxAge:   300,
		HttpOnly: true,
		Secure:   ssl,
		SameSite: http.SameSiteLaxMode,
	})
}

func GetStateCookie(r *http.Request) ([]byte, error) {
	if r == nil {
		return nil, errors.New("Request cannot be nil")
	}
	cookie, err := r.Cookie("oauth_uak")
	if err != nil {
		return nil, err
	}
	uak, err := base64.RawURLEncoding.DecodeString(cookie.Value)
	if err != nil {
		return nil, errors.Wrap(err, "failed to decode userAgentKey from cookie")
	}
	return uak, nil
}

func DeleteStateCookie(w http.ResponseWriter) {
	http.SetCookie(w, &http.Cookie{
		Name:   "oauth_uak",
		Value:  "",
		Path:   "/",
		MaxAge: -1,
	})
}
