package logic

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

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

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

func (l *AddGrowthRecordLogic) AddGrowthRecord(in *plant.AddGrowthRecordReq) (*plant.CommonResp, error) {
	err := l.svcCtx.DB.Transaction(func(tx *gorm.DB) error {
		record := plantModel.GrowthRecord{
			UserID: in.UserId, PlantID: in.PlantId, Content: in.Content,
		}
		if err := tx.Create(&record).Error; err != nil {
			return err
		}
		// 保存图片关联
		if len(in.ImgIds) > 0 {
			relations := make([]plantModel.GrowthRecordOss, 0, len(in.ImgIds))
			for _, ossId := range in.ImgIds {
				relations = append(relations, plantModel.GrowthRecordOss{
					GrowthRecordID: record.ID, OssID: ossId,
				})
			}
			if err := tx.Create(&relations).Error; err != nil {
				return err
			}
		}
		return nil
	})
	if err != nil {
		return nil, err
	}
	return &plant.CommonResp{Code: 0, Msg: "ok"}, nil
}
