package user

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/user"
	"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 GetUserLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

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

func (l *GetUserLogic) GetUser(in *core.UserReq) (*core.UserInfo, error) {
	var predicates []predicate.User
	if in.ID != 0 {
		predicates = append(predicates, user.IDEQ(in.ID))
		goto Query
	}
	if in.Username != "" {
		predicates = append(predicates, user.UsernameEQ(in.Username))
	}
	if in.PhoneNumber != "" {
		predicates = append(predicates, user.PhoneNumberEQ(in.PhoneNumber))
	}
	if in.Email != "" {
		predicates = append(predicates, user.EmailEQ(in.Email))
	}
	if in.Nickname != "" {
		predicates = append(predicates, user.NicknameEQ(in.Nickname))
	}
	if len(predicates) == 0 {
		return nil, nil
	}
Query:
	query := l.svcCtx.DB.User.Query().
		Where(predicates...).
		WithLoginRecord()
	if in.WithRole {
		query.WithRoles()
	}
	if in.WithSocial {
		query.WithSocials()
	}
	if in.WithDepartment {
		query.WithDepartments()
	}
	if in.WithToken {
		query.WithToken()
	}
	dbData, err := query.First(l.ctx)
	if err != nil {
		return nil, hander.HandleEntErr(err, in)
	}
	return l.svcCtx.Convert.ConvertUserRpc(l.ctx, dbData), nil
}
