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 UpdateWikiLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

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

func (l *UpdateWikiLogic) UpdateWiki(in *plant.UpdateWikiReq) (*plant.CommonResp, error) {
	classID := in.ClassId
	if classID == "" && len(in.ClassIds) > 0 {
		classID = in.ClassIds[0]
	}
	updates := map[string]interface{}{
		"name": in.Name, "latin_name": in.LatinName, "aliases": in.Aliases,
		"genus": in.Genus, "difficulty": in.Difficulty, "is_hot": in.IsHot,
		"growth_habit": in.GrowthHabit, "light_intensity": in.LightIntensity,
		"optimal_temp_period": in.OptimalTempPeriod, "class_id": classID,
		"distribution_area": in.DistributionArea, "life_cycle": in.LifeCycle,
		"reproduction_method": in.ReproductionMethod, "pests_diseases": in.PestsDiseases,
		"light_type": in.LightType, "stem": in.Stem, "fruit": in.Fruit,
		"foliage_type": in.FoliageType, "foliage_color": in.FoliageColor,
		"foliage_shape": in.FoliageShape, "height": in.Height,
		"flowering_period": in.FloweringPeriod, "flowering_color": in.FloweringColor,
		"flowering_shape": in.FloweringShape, "flower_diameter": in.FloweringDiameter,
		"is_vector_synced": false,
	}
	if err := l.svcCtx.DB.Transaction(func(tx *gorm.DB) error {
		if err := tx.Model(&plantModel.Wiki{}).Where("id = ?", in.Id).Updates(updates).Error; err != nil {
			return err
		}
		return replaceWikiRelations(tx, in.Id, in.ClassIds, in.OssIds, in.RelatedWikiIds)
	}); err != nil {
		return nil, err
	}
	go func() {
		_, _ = NewSyncWikiVectorLogic(context.Background(), l.svcCtx).SyncWikiVector(&plant.SyncWikiVectorReq{WikiId: in.Id})
	}()
	return &plant.CommonResp{Code: 0, Msg: "ok"}, nil
}
