// Code scaffolded by goctl. Safe to edit.
// goctl 1.9.2

package shop

import (
	"context"
	"errors"

	"juwan-backend/app/shop/api/internal/svc"
	"juwan-backend/app/shop/api/internal/types"
	"juwan-backend/app/shop/rpc/pb"
	"juwan-backend/common/utils/contextj"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdateShopLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// 更新店铺信息
func NewUpdateShopLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateShopLogic {
	return &UpdateShopLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UpdateShopLogic) UpdateShop(req *types.UpdateShopReq) (resp *types.ShopProfile, err error) {
	userID, err := contextj.UserIDFrom(l.ctx)
	if err != nil {
		return nil, err
	}

	current, err := l.svcCtx.ShopRpc.GetShopsById(l.ctx, &pb.GetShopsByIdReq{Id: req.Id})
	if err != nil {
		return nil, err
	}
	if current.Shops == nil {
		return nil, errors.New("shop not found")
	}
	if current.Shops.OwnerId != userID {
		return nil, contextj.ERRILLEGALUSER
	}
	logx.Debugf("update shop %+v", req)

	name := current.Shops.Name
	if req.Name != "" {
		name = req.Name
	}
	description := current.Shops.Description
	if req.Description != "" {
		description = req.Description
	}
	commissionType := current.Shops.CommissionType
	if req.CommissionType != "" {
		commissionType = req.CommissionType
	}
	commissionValue := current.Shops.CommissionValue
	if req.CommissionValue != "" {
		commissionValue = req.CommissionValue
	}
	dispatchMode := current.Shops.DispatchMode
	if req.DispatchMode != "" {
		dispatchMode = req.DispatchMode
	}

	_, err = l.svcCtx.ShopRpc.UpdateShops(l.ctx, &pb.UpdateShopsReq{
		Id:                     current.Shops.Id,
		OwnerId:                current.Shops.OwnerId,
		Name:                   name,
		Banner:                 current.Shops.Banner,
		Description:            description,
		Rating:                 current.Shops.Rating,
		TotalOrders:            current.Shops.TotalOrders,
		PlayerCount:            current.Shops.PlayerCount,
		CommissionType:         commissionType,
		CommissionValue:        commissionValue,
		AllowMultiShop:         req.AllowMultiShop,
		AllowIndependentOrders: req.AllowIndependentOrders,
		DispatchMode:           dispatchMode,
		Announcements:          current.Shops.Announcements,
		TemplateConfig:         current.Shops.TemplateConfig,
	})
	if err != nil {
		return nil, err
	}

	updated, err := l.svcCtx.ShopRpc.GetShopsById(l.ctx, &pb.GetShopsByIdReq{Id: req.Id})
	if err != nil {
		return nil, err
	}
	return toShopProfile(updated.Shops), nil

}
