package merchant

import (
	"context"

	"kami/api/merchant/v1"
	"kami/internal/consts"
	"kami/internal/model/do"
	"kami/internal/service"
	"kami/utility/config"

	"github.com/gogf/gf/v2/crypto/gmd5"
	"github.com/gogf/gf/v2/database/gdb"
	"github.com/gogf/gf/v2/text/gstr"
	"github.com/rs/xid"
)

func (c *ControllerV1) MerchantConfigAdd(ctx context.Context, req *v1.MerchantConfigAddReq) (res *v1.MerchantConfigAddRes, err error) {
	res = new(v1.MerchantConfigAddRes)
	err = config.GetDatabaseV1().Transaction(ctx, func(ctx context.Context, tx gdb.TX) error {
		// 添加商户
		merchantUid := "8888" + xid.New().String()
		err = service.Merchant().Add(ctx, do.V1MerchantInfo{
			Status:          req.Status,
			BelongAgentUid:  "",
			BelongAgentName: "",
			MerchantName:    req.MerchantName,
			MerchantUid:     merchantUid,
			MerchantKey:     "kkkk" + xid.New().String(),
			MerchantSecret:  "ssss" + xid.New().String(),
			LoginAccount:    req.LoginAccount,
			AutoPayFor:      consts.StatusNo,
			AutoSettle:      consts.StatusNo,
			LoginPassword:   gstr.ToUpper(gmd5.MustEncryptString(req.LoginPassword)),
			Remark:          req.Remark,
		}, tx)
		if err != nil {
			return err
		}
		err = service.Account().Add(ctx, do.V1AccountInfo{
			Status:      consts.StatusActive,
			AccountUid:  merchantUid,
			AccountName: req.MerchantName,
		}, tx)
		return err
	})
	return
}
