package merchant

import (
	"context"

	"kami/internal/service"
	"kami/utility/config"
	"kami/utility/lib/libErr"

	"github.com/gogf/gf/v2/database/gdb"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/os/glog"

	"github.com/gogf/gf/v2/errors/gerror"

	"kami/api/merchant/v1"
)

func (c *ControllerV1) MerchantConfigStatus(ctx context.Context, req *v1.MerchantConfigStatusReq) (res *v1.MerchantConfigStatusRes, err error) {
	m := service.Merchant()
	merchantInfo, err := m.GetMerchantByUId(ctx, req.MerchantUid)
	if err != nil {
		err = gerror.New("当前商户不存在")
		return
	}

	a := service.Account()
	accountInfo, err := a.GetAccountByUId(ctx, req.MerchantUid)
	if err != nil {
		err = gerror.New("获取商户账号信息失败")
		return
	}
	err = config.GetDatabaseV1().Transaction(ctx, func(ctx context.Context, tx gdb.TX) error {
		err = g.Try(ctx, func(ctx context.Context) {
			if req.Status != merchantInfo.Status {
				merchantInfo.Status = req.Status
				err = m.HandleStatus(ctx, merchantInfo, tx)
				libErr.ErrIsNil(ctx, err, "更新商户状态失败")
			}
			if req.Status != accountInfo.Status {
				accountInfo.Status = req.Status
				err = a.HandleStatus(ctx, accountInfo, tx)
				libErr.ErrIsNil(ctx, err, "更新商户钱包状态失败")
			}
		})
		return err
	})
	if err != nil {
		glog.Error(ctx, "更新商户状态失败", err)
		err = gerror.New("更新商户状态失败")
	}
	return
}
