package dictionary

import (
	"context"
	"git.noahlan.cn/n-admin/n-admin-server/dal/errx"
	"git.noahlan.cn/n-admin/n-admin-server/rpc/core/ent"
	"git.noahlan.cn/n-admin/n-admin-server/rpc/core/ent/dictionary"
	"git.noahlan.cn/n-admin/n-admin-server/rpc/core/internal/utils/entx"
	"git.noahlan.cn/n-admin/n-admin-server/rpc/core/internal/utils/hander"
	"git.noahlan.cn/noahlan/ntool-biz/core/nstatus"
	"git.noahlan.cn/noahlan/ntool-biz/core/nstatus/code"
	"git.noahlan.cn/noahlan/ntool-biz/core/nstatus/msg"
	"git.noahlan.cn/noahlan/ntool-biz/core/orm/nent/types"

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

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

// Dictionary Management
func (l *CreateDictionaryLogic) CreateDictionary(in *core.DictionaryInfo) (*core.BaseIDResp, error) {
	var dbData *ent.Dictionary
	if err := entx.WithTx(l.ctx, l.svcCtx.DB, func(tx *ent.Tx) error {
		var err error
		if err := l.preCheck(tx, in); err != nil {
			return err
		}
		dbData, err = tx.Dictionary.Create().
			SetStatus(types.ParseStatus(in.Status)).
			SetTitle(in.Title).
			SetName(in.Name).
			SetDescription(in.Description).Save(l.ctx)
		if err != nil {
			return hander.HandleEntErr(err, in)
		}
		return nil
	}); err != nil {
		return nil, err
	}
	return &core.BaseIDResp{
		ID:   dbData.ID,
		Code: code.StatusOK,
		Msg:  msg.CreateSuccess,
	}, nil
}

func (l *CreateDictionaryLogic) preCheck(tx *ent.Tx, in *core.DictionaryInfo) error {
	if in.Name == "" {
		return nstatus.NewBizErrWithCode(errx.DictionaryNameNotEmpty)
	} else {
		exist, err := tx.Dictionary.Query().Where(dictionary.NameEQ(in.Name)).Exist(l.ctx)
		if err != nil {
			return hander.HandleEntErr(err, in)
		}
		if exist {
			return nstatus.NewBizErrWithCode(errx.DictionaryNameInUsed)
		}
	}
	return nil
}
