package dictionary

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

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

func (l *GetDictionaryDetailLogic) GetDictionaryDetail(in *core.DictionaryDetailReq) (*core.DictionaryDetailInfo, error) {
	var predicates []predicate.DictionaryDetail
	if in.ID != 0 {
		predicates = append(predicates, dictionarydetail.IDEQ(in.ID))
		goto Query
	}
	if in.DictId != 0 {
		predicates = append(predicates, dictionarydetail.DictionaryIDEQ(in.DictId))
	}
	if in.Title != "" {
		predicates = append(predicates, dictionarydetail.TitleContains(in.Title))
	}
	if in.Key != "" {
		predicates = append(predicates, dictionarydetail.KeyEQ(in.Key))
	}
	if in.Value != "" {
		predicates = append(predicates, dictionarydetail.ValueEQ(in.Value))
	}
	if len(predicates) == 0 {
		return nil, nil
	}
Query:
	query := l.svcCtx.DB.DictionaryDetail.Query().Where(predicates...)
	if in.WithDictionary {
		query.WithDictionary()
	}
	dbData, err := query.First(l.ctx)
	if err != nil {
		return nil, hander.HandleEntErr(err, in)
	}
	return l.svcCtx.Convert.ConvertDictionaryDetailRpc(l.ctx, dbData), nil
}
