package users

import (
	"context"
	"net/http"

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

func HandleUsers(w http.ResponseWriter, r *http.Request) {
	var users []models.User
	count, err := core.DB.NewSelect().
		Model(&users).
		Order("created_at ASC").
		Relation("Roles").
		ScanAndCount(context.Background())

	users = utils.Map(users, func(user models.User) models.User {
		user.Password = ""
		return user
	})

	if count == 0 {
		core.JSONSuccess{
			Status:  core.Success,
			Message: "No users.",
		}.Respond(w, http.StatusNotFound)
		return
	}

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

	core.JSONSuccess{
		Status:  core.Success,
		Message: "Users found.",
		Data:    users,
	}.Respond(w, http.StatusOK)
}
