package dictionary

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

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

func (l *GetDictionaryLogic) GetDictionary(in *core.DictionaryReq) (*core.DictionaryInfo, error) {
	var predicates []predicate.Dictionary
	if in.ID != 0 {
		predicates = append(predicates, dictionary.IDEQ(in.ID))
		goto Query
	}
	if in.Name != "" {
		predicates = append(predicates, dictionary.NameEQ(in.Name))
	}
	if in.Title != "" {
		predicates = append(predicates, dictionary.TitleEQ(in.Title))
	}
	if len(predicates) == 0 {
		return nil, nil
	}
Query:
	query := l.svcCtx.DB.Dictionary.Query().Where(predicates...)
	if in.WithDetails {
		query.WithDetails()
	}
	dbData, err := query.First(l.ctx)
	if err != nil {
		return nil, hander.HandleEntErr(err, in)
	}

	return l.svcCtx.Convert.ConvertDictionaryRpc(l.ctx, dbData), nil
}
