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

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

func (l *UpdateTopicLogic) UpdateTopic(in *plant.UpdateTopicReq) (*plant.CommonResp, error) {
	name := in.Name
	if name == "" {
		name = in.Title
	}
	updates := map[string]interface{}{"name": name, "title": in.Title, "icon": in.Icon, "desc": in.Desc, "remark": in.Remark}
	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.Topic{}).Where("id = ?", in.Id).Updates(updates).Error; err != nil {
		return nil, err
	}
	return &plant.CommonResp{Code: 0, Msg: "ok"}, nil
}
