package users

import (
	"context"
	"encoding/json"
	"log"
	"net/http"

	core "fr.latosa-escrima/core"
	"fr.latosa-escrima/core/models"
	"fr.latosa-escrima/utils"
)

func HandleNew(w http.ResponseWriter, r *http.Request) {
	ctx := context.Background()
	var user models.User
	err := json.NewDecoder(r.Body).Decode(&user)
	if err != nil {
		core.JSONError{
			Status:  core.Error,
			Message: err.Error(),
		}.Respond(w, http.StatusNotAcceptable)
		return
	}
	log.Println("User : ", user)

	res, err := user.Insert(core.DB, ctx)
	log.Println(res)

	if err != nil {
		core.JSONError{
			Status:  core.Error,
			Message: err.Error(),
		}.Respond(w, http.StatusInternalServerError)
		return
	}

	userRoles := utils.Map(user.Roles, func(role models.Role) models.UserToRole {
		return models.UserToRole{
			UserID: user.UserID,
			RoleID: role.ID,
		}
	})

	for _, userRole := range userRoles {
		_, err := core.DB.NewInsert().Model(&userRole).Ignore().Exec(ctx)
		if err != nil {
			core.JSONError{
				Status:  core.Error,
				Message: err.Error(),
			}.Respond(w, http.StatusInternalServerError)
			return
		}
	}

	core.JSONSuccess{
		Status:  core.Success,
		Message: "User inserted successfully.",
		Data:    nil,
	}.Respond(w, http.StatusCreated)
}
