package role

import (
	"context"
	"git.noahlan.cn/n-admin/n-admin-server/rpc/core/ent/predicate"
	"git.noahlan.cn/n-admin/n-admin-server/rpc/core/ent/role"
	"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 GetRoleLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

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

func (l *GetRoleLogic) GetRole(in *core.RoleReq) (*core.RoleInfo, error) {
	var predicates []predicate.Role
	if in.ID != 0 {
		predicates = append(predicates, role.IDEQ(in.ID))
		goto Query
	}
	if in.Name != "" {
		predicates = append(predicates, role.NameContains(in.Name))
	}
	if in.Code != "" {
		predicates = append(predicates, role.CodeEQ(in.Code))
	}
	if len(predicates) == 0 {
		return nil, nil
	}
Query:
	query := l.svcCtx.DB.Role.Query().Where(predicates...)
	if in.WithUser {
		query.WithUsers()
	}
	dbData, err := query.First(l.ctx)
	if err != nil {
		return nil, hander.HandleEntErr(err, in)
	}
	return l.svcCtx.Convert.ConvertRoleRpc(l.ctx, dbData), nil
}
