package user

import (
	"bsm/full/module/base/mgt/internal/impl"
	"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"
	"github.com/gin-gonic/gin"
)

func UserList(c *gin.Context) {
	var (
		request = types.FetchBase{}
		data    = make([]types.UserResp, 0)
	)
	err := c.ShouldBindJSON(&request)
	if err != nil {
		infra.Response.Error(c, errcode.ErrJsonUnmarshal)
		return
	}
	if request.Workspace == "" {
		infra.Response.Error(c, errcode.ErrInvalidArgument)
		return
	}

	db := impl.DBService.Model(&models.MgtUser{}).
		Where("id IN (SELECT user_id FROM mgt_link_user_app WHERE app_id = (SELECT id FROM mgt_application WHERE workspace = ? LIMIT 1))", request.Workspace)
	if request.Keyword != "" {
		likeStr := "%" + request.Keyword + "%"
		db = db.Where("name LIKE ?", likeStr)
	}
	if request.Status != 0 {
		db = db.Where("status = ?", request.Status)
	}
	if err := db.Find(&data).Error; err != nil {
		infra.Response.Error(c, errcode.ErrDB)
		return
	}
	infra.Response.Success(c, types.FetchResp{Data: data})
}
