package user

import (
	// External
	"github.com/golang-jwt/jwt/v5"
	"github.com/jmoiron/sqlx"

	// Standard
	"encoding/json"
)

type User struct {
	ID          int
	Username    string
	Name        string
	Preferences map[string]UserPreferences
}

type UserSession struct {
	UserID     int
	Username   string
	Password   string
	Name       string
	ClientUUID string
	Db         *sqlx.DB
}

type UserPreferences struct {
	DownloadImages bool
	DownloadFiles  bool
}

func NewUser(claims jwt.MapClaims) (u UserSession) {
	uid, _ := claims["uid"].(float64)
	name, _ := claims["name"].(string)
	username, _ := claims["login"].(string)
	clientUUID, _ := claims["cid"].(string)

	u.UserID = int(uid)
	u.Username = username
	u.Name = name
	u.ClientUUID = clientUUID
	return
}

func (u UserSession) Preferences() (prefs map[string]UserPreferences, err error) {
	row := u.Db.QueryRow(`SELECT preferences FROM public.user WHERE id=$1`, u.UserID)

	var data []byte
	err = row.Scan(&data)
	if err != nil {
		return
	}

	err = json.Unmarshal(data, &prefs)
	return
}

func (u UserSession) SetPreferences(prefs map[string]UserPreferences) (err error) {
	j, _ := json.Marshal(prefs)
	_, err = u.Db.Exec(`UPDATE public.user SET preferences=$2 WHERE id=$1`, u.UserID, j)
	return
}
