package logic

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

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

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

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

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

func (l *UpdateShopsLogic) UpdateShops(in *pb.UpdateShopsReq) (*pb.UpdateShopsResp, error) {
	updater := l.svcCtx.ShopModelRW.Shops.UpdateOneID(in.Id)

	if in.OwnerId > 0 {
		updater = updater.SetOwnerID(in.OwnerId)
	}
	if in.Name != "" {
		updater = updater.SetName(in.Name)
	}
	if in.Banner != "" {
		updater = updater.SetBanner(in.Banner)
	}
	if in.Description != "" {
		updater = updater.SetDescription(in.Description)
	}
	if in.Rating != "" {
		rating, perr := decimal.NewFromString(in.Rating)
		if perr != nil {
			return nil, errors.New("invalid rating")
		}
		updater = updater.SetRating(rating)
	}
	if in.TotalOrders > 0 {
		updater = updater.SetTotalOrders(int(in.TotalOrders))
	}
	if in.PlayerCount > 0 {
		updater = updater.SetPlayerCount(int(in.PlayerCount))
	}
	if in.CommissionType != "" {
		updater = updater.SetCommissionType(in.CommissionType)
	}
	if in.CommissionValue != "" {
		commissionValue, perr := decimal.NewFromString(in.CommissionValue)
		if perr != nil {
			return nil, errors.New("invalid commissionValue")
		}
		updater = updater.SetCommissionValue(commissionValue)
	}
	if in.DispatchMode != "" {
		updater = updater.SetDispatchMode(in.DispatchMode)
	}

	updater = updater.
		SetAllowMultiShop(in.AllowMultiShop).
		SetAllowIndependentOrders(in.AllowIndependentOrders)

	if len(in.Announcements) > 0 {
		updater = updater.SetAnnouncements(schema.TextArray{Elements: in.Announcements, Valid: true})
	}

	if in.TemplateConfig != "" {
		var templateConfig map[string]interface{}
		err := json.Unmarshal([]byte(in.TemplateConfig), &templateConfig)
		if err != nil {
			logx.WithContext(l.ctx).Errorf("invalid template config: %v", err)
			return nil, errors.New("invalid template config")
		}
		updater = updater.SetTemplateConfig(templateConfig)
	}

	if in.UpdatedAt > 0 {
		updater = updater.SetUpdatedAt(time.Unix(in.UpdatedAt, 0))
	}

	_, err := updater.Where(shops.IDEQ(in.Id)).Save(l.ctx)
	if err != nil {
		logx.WithContext(l.ctx).Errorf("update shops failed: %v", err)
		return nil, errors.New("update shops failed")
	}

	return &pb.UpdateShopsResp{}, nil
}
