package user

import (
	"bsm/full/module/base/mgt/internal/impl"
	"bsm/full/module/base/mgt/internal/libs"
	mgtmw "bsm/full/module/base/mgt/internal/middleware"
	"bsm/full/module/base/mgt/internal/models"
	"bsm/full/module/base/mgt/internal/types"

	"git.apinb.com/bsm-sdk/core/errcode"
	"git.apinb.com/bsm-sdk/core/infra"
	"git.apinb.com/bsm-sdk/core/middleware"
	"github.com/gin-gonic/gin"
)

func ApplicationsFetch(c *gin.Context) {
	var (
		request = types.FetchBase{}
		data    = make([]models.MgtUser, 0)
		db      = impl.DBService.Model(&models.MgtUser{})
	)
	if err := c.ShouldBindJSON(&request); err != nil {
		infra.Response.Error(c, errcode.ErrJsonUnmarshal)
		return
	}

	if err := libs.ValidateStruct(&request); err != nil {
		infra.Response.Error(c, errcode.ErrInvalidArgument)
		return
	}

	auth, err := middleware.ParseAuth(c)
	if err != nil {
		infra.Response.Error(c, errcode.ErrTokenAuthParseFail)
		return
	}

	if request.ID == 0 {
		request.ID = auth.ID
	}
	if !mgtmw.EnsureSelfOrAdmin(c, request.ID) {
		return
	}

	db = db.Where("id = ?", request.ID)
	if err := db.Select("id", "identity", "name").Preload("Application").Find(&data).Error; err != nil {
		infra.Response.Error(c, errcode.ErrDB)
		return
	}
	infra.Response.Success(c, data)
}
