package bookmark

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/service"
)

// 获取书签列表
func ListBookmarks(ctx context.Context, in *pb.FetchRequest) (reply *pb.ListBookmarksResponse, err error) {
	// parse authorization meta.
	auth, err := service.ParseMetaCtx(ctx, nil)
	if err != nil {
		return nil, err
	}

	// validate request page_no,page_size.
	if in.GetPageNo() < 1 {
		in.PageNo = 1
	}
	if in.GetPageSize() < 10 {
		in.PageSize = 50
	}

	// logic code
	var bookmarks []models.CloudBookmark
	var total int64

	// 获取总数
	if err := impl.DBService.Model(&models.CloudBookmark{}).Where("passport_id = ?", auth.ID).Count(&total).Error; err != nil {
		return nil, err
	}

	// 分页查询
	offset := (in.PageNo - 1) * in.PageSize
	if err := impl.DBService.Where("passport_id = ?", auth.ID).
		Order("created_at DESC").
		Offset(int(offset)).
		Limit(int(in.PageSize)).
		Find(&bookmarks).Error; err != nil {
		return nil, err
	}

	// 转换数据
	var bookmarkItems []*pb.CloudBookmarkItem
	for _, bookmark := range bookmarks {
		bookmarkItems = append(bookmarkItems, &pb.CloudBookmarkItem{
			Id:          uint64(bookmark.ID),
			Identity:    bookmark.Identity,
			Title:       bookmark.Title,
			Url:         bookmark.URL,
			Description: bookmark.Description,
			Category:    bookmark.Category,
			Tags:        bookmark.Tags,
			Icon:        bookmark.Icon,
			IsPrivate:   bookmark.IsPrivate,
			CreatedAt:   bookmark.CreatedAt.Format(time.RFC3339),
			UpdatedAt:   bookmark.UpdatedAt.Format(time.RFC3339),
		})
	}

	reply = &pb.ListBookmarksResponse{
		Bookmarks: bookmarkItems,
		Total:     total,
	}

	return reply, nil
}
