package logic

import (
	"context"
	"time"

	"github.com/zeromicro/go-zero/core/logx"
	plantModel "sundynix-micro-go/app/plant/model"
	"sundynix-micro-go/app/plant/rpc/internal/svc"
	"sundynix-micro-go/app/plant/rpc/plant"
)

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

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

func (l *UpdateExchangeItemLogic) UpdateExchangeItem(in *plant.UpdateExchangeItemReq) (*plant.CommonResp, error) {
	cost := in.Cost
	if in.CostSunlight > 0 {
		cost = in.CostSunlight
	}
	imgID := in.ImgId
	if imgID == "" {
		imgID = in.ImageId
	}
	updates := map[string]interface{}{
		"name": in.Name, "desc": in.Desc, "description": in.Desc, "img_id": imgID, "image_id": imgID,
		"cost": cost, "cost_sunlight": cost, "stock": in.Stock, "status": in.Status,
		"type": in.Type, "limit_per_user": in.LimitPerUser, "sort": in.Sort,
	}
	if in.StartTime != "" {
		if t, err := time.Parse(time.DateTime, in.StartTime); err == nil {
			updates["start_time"] = &t
		}
	}
	if in.EndTime != "" {
		if t, err := time.Parse(time.DateTime, in.EndTime); err == nil {
			updates["end_time"] = &t
		}
	}
	if err := l.svcCtx.DB.Model(&plantModel.ExchangeItem{}).Where("id = ?", in.Id).Updates(updates).Error; err != nil {
		return nil, err
	}
	return &plant.CommonResp{Code: 0, Msg: "ok"}, nil
}
