package session

import (
	"encoding/json"
	"fmt"
	"log/slog"
	"net/http"
	"os"
	"path"

	"github.com/gorilla/securecookie"
	"github.com/gorilla/sessions"
	"github.com/spf13/viper"
)

var SessionStore sessions.FilesystemStore

func InitSessions() {
	SessionStore = sessionStore()
}

func sessionStore() sessions.FilesystemStore {
	var key []byte
	if keystring := viper.GetString("web.session.key"); keystring != "" {
		key = []byte(keystring)
	} else {
		key = securecookie.GenerateRandomKey(32)
	}
	sessionPath := viper.GetString("web.session.path")
	if path.IsAbs(sessionPath) == false {
		workdir, err := os.Getwd()
		if err != nil {
			slog.Error("Error determining working directory", "error", err)
			panic(err)
		}
		sessionPath = path.Join(workdir, sessionPath)
	}

	slog.Info(fmt.Sprint("Session store set to ", sessionPath))
	return *sessions.NewFilesystemStore(sessionPath, key)
}

func serializeToJSON(slice []string) (string, error) {
	jsonData, err := json.Marshal(slice)
	if err != nil {
		return "", err
	}
	return string(jsonData), nil
}

func deserializeFromJSON(data string) ([]string, error) {
	var slice []string
	err := json.Unmarshal([]byte(data), &slice)
	return slice, err
}

func GetSession(r *http.Request) *sessions.Session {
	session, err := SessionStore.Get(r, "fileserver")
	if err != nil {
		slog.Info(fmt.Sprintf("Error getting session for RemoteAddr %s: %s", r.RemoteAddr, err))
		return nil
	}
	return session
}
