package logic

import (
	"context"
	"encoding/json"
	"errors"
	"juwan-backend/app/shop/rpc/internal/models/shops"

	"juwan-backend/app/shop/rpc/internal/svc"
	"juwan-backend/app/shop/rpc/pb"

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

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

func NewGetShopsByIdLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetShopsByIdLogic {
	return &GetShopsByIdLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *GetShopsByIdLogic) GetShopsById(in *pb.GetShopsByIdReq) (*pb.GetShopsByIdResp, error) {
	shop, err := l.svcCtx.ShopModelRO.Shops.Query().Where(shops.IDEQ(in.Id)).First(l.ctx)
	if err != nil {
		logx.WithContext(l.ctx).Errorf("GetShopsByIdLogic err: %v", err)
		return nil, errors.New("get shops by id failed")
	}

	templateConfigBytes, err := json.Marshal(shop.TemplateConfig)
	if err != nil {
		logx.WithContext(l.ctx).Errorf("GetShopsByIdLogic marshal template config err: %v", err)
		return nil, errors.New("get shops by id failed")
	}

	pbShop := pb.Shops{
		Id:                     shop.ID,
		OwnerId:                shop.OwnerID,
		Name:                   shop.Name,
		Rating:                 shop.Rating.String(),
		TotalOrders:            int64(shop.TotalOrders),
		PlayerCount:            int64(shop.PlayerCount),
		CommissionType:         shop.CommissionType,
		CommissionValue:        shop.CommissionValue.String(),
		AllowMultiShop:         shop.AllowMultiShop,
		AllowIndependentOrders: shop.AllowIndependentOrders,
		DispatchMode:           shop.DispatchMode,
		Announcements:          shop.Announcements.Elements,
		TemplateConfig:         string(templateConfigBytes),
		CreatedAt:              shop.CreatedAt.Unix(),
		UpdatedAt:              shop.UpdatedAt.Unix(),
	}
	if shop.Banner != nil {
		pbShop.Banner = *shop.Banner
	}
	if shop.Description != nil {
		pbShop.Description = *shop.Description
	}

	return &pb.GetShopsByIdResp{Shops: &pbShop}, nil
}
