package middlewares

// |@@| C

import (
	"crypto/rand"
	"github.com/gin-contrib/sessions"
	"github.com/gin-contrib/sessions/cookie"
	"github.com/gin-gonic/gin"
	"net/http"
)

// TODO Move the keys generation to env values, and the adding to env values process into init phase via dev tooling

type SessionMiddleware struct {
}

func (this *SessionMiddleware) Act() gin.HandlerFunc {
	return sessions.Sessions("session", this.newStore())
}

func GenerateRandomBytes(n int) ([]byte, error) {
	key := make([]byte, n)
	_, err := rand.Read(key)
	if err != nil {
		return nil, err
	}
	return key, nil
}

func GenerateKeyPair() ([][]byte, error) {
	authKey, err := GenerateRandomBytes(32) // 32 bytes for HMAC (authentication)
	if err != nil {
		return nil, err
	}

	encKey, err := GenerateRandomBytes(32) // 32 bytes for AES-256
	if err != nil {
		return nil, err
	}

	return [][]byte{authKey, encKey}, nil
}

func (this *SessionMiddleware) newStore() cookie.Store {
	//keys, err := GenerateKeyPair()
	//if err != nil {
	//	lib.Poe(erro.N("Cannot generate secret for cookie store"))
	//}
	//return cookie.NewStore(keys...)
	store := cookie.NewStore([]byte("secret"))

	store.Options(sessions.Options{
		Path:     "/",                     // Cookie valid across the entire site
		MaxAge:   3600 * 24,               // Session expiration: 24 hours
		HttpOnly: true,                    // Prevent access via JavaScript (mitigates XSS)
		Secure:   true,                    // Cookie is only sent over HTTPS
		SameSite: http.SameSiteStrictMode, // Strict: Completely disallows third-party access
	})

	return store
}
