package note

import (
	"context"
	"time"

	"bsm/full/module/base/cloud/internal/impl"
	"bsm/full/module/base/cloud/internal/models"
	pb "bsm/full/module/base/cloud/pb"
	"git.apinb.com/bsm-sdk/core/errcode"
	"git.apinb.com/bsm-sdk/core/printer"
	"git.apinb.com/bsm-sdk/core/service"
	"git.apinb.com/bsm-sdk/core/vars"
)

// 置顶/取消置顶笔记
func TogglePin(ctx context.Context, in *pb.TogglePinRequest) (reply *pb.StatusReply, err error) {
	// parse authorization meta.
	auth, err := service.ParseMetaCtx(ctx, nil)
	if err != nil {
		return nil, err
	}

	// validate request
	if in.Id == 0 {
		return nil, errcode.ErrInvalidArgument
	}

	// logic code
	var note models.CloudNote
	if err := impl.DBService.Where("id = ? AND passport_id = ?", in.Id, auth.ID).First(&note).Error; err != nil {
		printer.Error("Note not found: %v", err)
		return nil, errcode.ErrInvalidArgument
	}

	// 更新置顶状态
	note.IsPinned = in.IsPinned

	if err := impl.DBService.Save(&note).Error; err != nil {
		printer.Error("Toggle pin error: %v", err)
		return nil, errcode.ErrDB
	}

	return &pb.StatusReply{
		Details: vars.OK,
		Timeseq: time.Now().UnixMilli(),
	}, nil
}
