package logic

import (
	"context"
	"errors"

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

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

// 收藏/取消收藏百科
func (l *ToggleWikiStarLogic) ToggleWikiStar(in *plant.ToggleStarReq) (*plant.CommonResp, error) {
	var star plantModel.UserStar
	err := l.svcCtx.DB.Where("user_id = ? AND target_id = ? AND type = ?", in.UserId, in.TargetId, in.Type).First(&star).Error
	if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
		return nil, err
	}
	if errors.Is(err, gorm.ErrRecordNotFound) {
		// 未收藏 → 创建
		newStar := plantModel.UserStar{
			UserID:   in.UserId,
			TargetID: in.TargetId,
			Type:     in.Type,
		}
		if err := l.svcCtx.DB.Create(&newStar).Error; err != nil {
			return nil, err
		}
		return &plant.CommonResp{Code: 0, Msg: "starred"}, nil
	}
	// 已收藏 → 取消
	if err := l.svcCtx.DB.Unscoped().Delete(&star).Error; err != nil {
		return nil, err
	}
	return &plant.CommonResp{Code: 0, Msg: "unstarred"}, nil
}
