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

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

func (l *UpdateDictionaryDetailLogic) UpdateDictionaryDetail(in *core.DictionaryDetailInfo) (*core.BaseResp, error) {
	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
		}

		update := tx.DictionaryDetail.Update()
		update.SetNotEmptyTitle(in.Title).
			SetNotEmptyKey(in.Key).
			SetValue(in.Value)
		if in.Sort != 0 {
			update.SetSort(in.Sort)
		}
		if in.Status != "" {
			update.SetStatus(types.ParseStatus(in.Status))
		}
		if in.DictionaryId != 0 {
			update.SetDictionaryID(in.DictionaryId)
		}
		err = update.Exec(l.ctx)
		if err != nil {
			return hander.HandleEntErr(err, in)
		}
		return nil
	}); err != nil {
		return nil, err
	}
	return &core.BaseResp{
		Code: code.StatusOK,
		Msg:  msg.UpdateSuccess,
	}, nil
}

func (l *UpdateDictionaryDetailLogic) preCheck(tx *ent.Tx, in *core.DictionaryDetailInfo) error {
	if in.ID == 0 {
		return nstatus.NewBizErrWithCode(errx.DictionaryDetailIdNotEmpty)
	}
	if in.Key == "" {
		return nstatus.NewBizErrWithCode(errx.DictionaryDetailKeyNotEmpty)
	}
	exist, err := tx.DictionaryDetail.Query().
		Where(dictionarydetail.KeyEQ(in.Key), dictionarydetail.IDEQ(in.ID)).
		Exist(l.ctx)
	if err != nil {
		return hander.HandleEntErr(err, in)
	}
	if exist {
		return nstatus.NewBizErrWithCode(errx.DictionaryDetailExists)
	}
	return nil
}
