package logic

import (
	"context"

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

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

// 删除帖子 (级联删除评论/点赞/图片关联)
func (l *DeletePostLogic) DeletePost(in *plant.IdsReq) (*plant.CommonResp, error) {
	err := l.svcCtx.DB.Transaction(func(tx *gorm.DB) error {
		tx.Exec("DELETE FROM sundynix_post_oss WHERE post_id IN ?", in.Ids)
		if err := tx.Unscoped().Where("post_id IN ?", in.Ids).Delete(&plantModel.PostLike{}).Error; err != nil {
			return err
		}
		if err := tx.Unscoped().Where("post_id IN ?", in.Ids).Delete(&plantModel.PostComment{}).Error; err != nil {
			return err
		}
		if err := tx.Unscoped().Where("id IN ?", in.Ids).Delete(&plantModel.Post{}).Error; err != nil {
			return err
		}
		return nil
	})
	if err != nil {
		return nil, err
	}
	return &plant.CommonResp{Code: 0, Msg: "ok"}, nil
}
