package user_role

import (
	"context"
	"git.noahlan.cn/n-admin/n-admin-server/rpc/core/ent"
	"git.noahlan.cn/n-admin/n-admin-server/rpc/core/ent/role"
	"git.noahlan.cn/n-admin/n-admin-server/rpc/core/ent/user"
	"git.noahlan.cn/n-admin/n-admin-server/rpc/core/internal/utils"
	"git.noahlan.cn/n-admin/n-admin-server/rpc/core/internal/utils/hander"

	"git.noahlan.cn/n-admin/n-admin-server/rpc/core/internal/svc"
	"git.noahlan.cn/n-admin/n-admin-server/rpc/core/types/core"
)

type GetUserRolesLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewGetUserRolesLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetUserRolesLogic {
	return &GetUserRolesLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

// GetUserRoles 获取用户绑定的角色列表
func (l *GetUserRolesLogic) GetUserRoles(in *core.GetUserRolesReq) (*core.RoleListResp, error) {
	var (
		pagination *core.Pagination
		list       []*ent.Role
		err        error
	)

	query := l.svcCtx.DB.Role.Query().Where(role.HasUsersWith(user.IDEQ(in.UserId)))
	if in.Page != nil {
		result, pageErr := query.Page(l.ctx, in.Page.Current, in.Page.Size)
		if pageErr == nil {
			pagination = utils.ConvertPaginationDb(result.PageDetails)
			list = result.List
		} else {
			err = pageErr
		}
	} else {
		list, err = query.All(l.ctx)
	}
	if err != nil {
		return nil, hander.HandleEntErr(err, in)
	}

	resp := &core.RoleListResp{
		Page: pagination,
		Data: make([]*core.RoleInfo, len(list)),
	}
	for i, v := range list {
		resp.Data[i] = l.svcCtx.Convert.ConvertRoleRpc(l.ctx, v)
	}

	return resp, nil
}
