package bookmark

import (
	"context"
	"strings"
	"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 UpdateBookmark(ctx context.Context, in *pb.CloudBookmarkItem) (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 && in.Identity == "" {
		return nil, errcode.ErrInvalidArgument
	}
	if strings.TrimSpace(in.Title) == "" {
		return nil, errcode.ErrInvalidArgument
	}
	if strings.TrimSpace(in.Url) == "" {
		return nil, errcode.ErrInvalidArgument
	}

	// logic code
	var bookmark models.CloudBookmark
	query := impl.DBService.Where("passport_id = ?", auth.ID)

	if in.Id > 0 {
		query = query.Where("id = ?", in.Id)
	} else {
		query = query.Where("identity = ?", in.Identity)
	}

	if err := query.First(&bookmark).Error; err != nil {
		printer.Error("Bookmark not found: %v", err)
		return nil, errcode.ErrInvalidArgument
	}

	// 更新字段
	bookmark.Title = in.Title
	bookmark.URL = in.Url
	bookmark.Description = in.Description
	bookmark.Category = in.Category
	bookmark.Tags = in.Tags
	bookmark.Icon = in.Icon
	bookmark.IsPrivate = in.IsPrivate

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

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