package logic

import (
	"context"
	"errors"
	"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 LikePostLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

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

func (l *LikePostLogic) LikePost(in *plant.LikePostReq) (*plant.CommonResp, error) {
	var existing plantModel.PostLike
	err := l.svcCtx.DB.Where("user_id = ? AND post_id = ?", in.UserId, in.PostId).First(&existing).Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		like := plantModel.PostLike{UserID: in.UserId, PostID: in.PostId}
		if err2 := l.svcCtx.DB.Create(&like).Error; err2 != nil {
			return nil, err2
		}
		l.svcCtx.DB.Model(&plantModel.Post{}).Where("id = ?", in.PostId).UpdateColumn("like_count", gorm.Expr("like_count + 1"))
	} else {
		l.svcCtx.DB.Delete(&existing)
		l.svcCtx.DB.Model(&plantModel.Post{}).Where("id = ?", in.PostId).UpdateColumn("like_count", gorm.Expr("GREATEST(like_count - 1, 0)"))
	}
	return &plant.CommonResp{Code: 0, Msg: "ok"}, nil
}
