package logic

import (
	"context"
	"errors"
	"time"

	plantModel "sundynix-micro-go/app/plant/model"
	"sundynix-micro-go/app/plant/rpc/internal/svc"
	"sundynix-micro-go/app/plant/rpc/plant"

	"github.com/zeromicro/go-zero/core/logx"
	"gorm.io/gorm"
)

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

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

// 创建话题
func (l *CreateTopicLogic) CreateTopic(in *plant.CreateTopicReq) (*plant.CommonResp, error) {
	name := in.Name
	if name == "" {
		name = in.Title
	}
	if !errors.Is(l.svcCtx.DB.Where("name = ? OR title = ?", name, in.Title).First(&plantModel.Topic{}).Error, gorm.ErrRecordNotFound) {
		return nil, errors.New("存在重复话题")
	}
	var start, end *time.Time
	if in.StartTime != "" {
		if t, err := time.Parse(time.DateTime, in.StartTime); err == nil {
			start = &t
		}
	}
	if in.EndTime != "" {
		if t, err := time.Parse(time.DateTime, in.EndTime); err == nil {
			end = &t
		}
	}
	topic := plantModel.Topic{Name: name, Title: in.Title, Icon: in.Icon, Desc: in.Desc, Remark: in.Remark, StartTime: start, EndTime: end}
	if err := l.svcCtx.DB.Create(&topic).Error; err != nil {
		return nil, err
	}
	return &plant.CommonResp{Code: 0, Msg: "ok"}, nil
}
