package user

import (
	"backend/dbRequest"
	"backend/models"
	"encoding/json"
	"fmt"
	"io"
	"net/http"

	"github.com/gin-gonic/gin"
)

func (um *UserManager) UpdateSettings(c *gin.Context) {
	if !um.databaseOpened(c) {
		return
	}

	body, err := io.ReadAll(c.Request.Body)
	if err != nil {
		c.JSON(http.StatusBadRequest, models.NewJsonErrorResponse(err))
		return
	}

	user := models.User{}
	err = json.Unmarshal(body, &user)
	if err != nil {
		c.JSON(http.StatusBadRequest, models.NewJsonErrorResponse(err))
		return
	}

	jsonBytes, err := json.Marshal(user.Settings)
	if err != nil {
		c.JSON(http.StatusOK, models.NewJsonErrorMessageResponse(err.Error()))
		return
	}

	if _, err := um.database.Exec(dbRequest.DBUpdateSettings, string(jsonBytes), user.Name); err != nil {
		c.JSON(http.StatusBadRequest, models.NewJsonErrorResponse(err))
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"message": fmt.Sprintf("user settings '%s' successfully updated", user.Name),
	})
}
