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

package shop

import (
	"context"
	"errors"

	"juwan-backend/app/shop/rpc/pb"
	"juwan-backend/common/utils/contextj"

	"juwan-backend/app/shop/api/internal/svc"
	"juwan-backend/app/shop/api/internal/types"

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

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

// 创建店铺
func NewCreateShopLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateShopLogic {
	return &CreateShopLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *CreateShopLogic) CreateShop(req *types.CreateShopReq) (resp *types.ShopProfile, err error) {
	ownerID, err := contextj.UserIDFrom(l.ctx)
	if err != nil {
		return nil, err
	}
	if ownerID == 0 {
		return nil, errors.New("user not authenticated")
	}

	if req.Name == "" {
		return nil, errors.New("name is required")
	}

	_, err = l.svcCtx.ShopRpc.AddShops(l.ctx, &pb.AddShopsReq{
		OwnerId:                ownerID,
		Name:                   req.Name,
		Description:            req.Description,
		Rating:                 "5",
		TotalOrders:            0,
		PlayerCount:            0,
		CommissionType:         req.CommissionType,
		CommissionValue:        req.CommissionValue,
		AllowMultiShop:         false,
		AllowIndependentOrders: true,
		DispatchMode:           "manual",
		Announcements:          []string{},
		TemplateConfig:         `{}`,
	})
	if err != nil {
		return nil, err
	}

	shop, err := getShopByOwnerID(l.ctx, l.svcCtx.ShopRpc, ownerID)
	if err != nil {
		return nil, err
	}
	if shop == nil {
		return nil, errors.New("create shop failed")
	}

	return toShopProfile(shop), nil

}
