package bookmark

import (
	"context"
	"encoding/json"
	"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/types"
	"git.apinb.com/bsm-sdk/core/utils"
	"git.apinb.com/bsm-sdk/core/vars"
)

// 导入书签
func ImportBookmarks(ctx context.Context, in *pb.ImportBookmarksRequest) (reply *pb.StatusReply, err error) {
	// parse authorization meta.
	auth, err := service.ParseMetaCtx(ctx, nil)
	if err != nil {
		return nil, err
	}

	// validate request
	if strings.TrimSpace(in.Data) == "" {
		return nil, errcode.ErrInvalidArgument
	}
	if strings.TrimSpace(in.Format) == "" {
		in.Format = "json"
	}

	// logic code
	// 解析JSON数据
	var bookmarks []map[string]interface{}
	if err := json.Unmarshal([]byte(in.Data), &bookmarks); err != nil {
		printer.Error("Parse bookmarks data error: %v", err)
		return nil, errcode.ErrInvalidArgument
	}

	// 批量创建书签
	var records []models.CloudBookmark
	for _, item := range bookmarks {
		title, _ := item["title"].(string)
		url, _ := item["url"].(string)
		description, _ := item["description"].(string)
		category, _ := item["category"].(string)
		tags, _ := item["tags"].(string)
		icon, _ := item["icon"].(string)
		isPrivate, _ := item["is_private"].(bool)

		if title == "" || url == "" {
			continue
		}

		record := models.CloudBookmark{
			Std_IICUDS: types.Std_IICUDS{
				Identity: utils.UUID(),
			},
			Std_Passport: types.Std_Passport{
				PassportID:       auth.ID,
				PassportIdentity: auth.Identity,
			},
			CloudBase: models.CloudBase{
				CloudID:       1, // 默认云空间ID
				CloudIdentity: "default",
			},
			Title:       title,
			URL:         url,
			Description: description,
			Category:    category,
			Tags:        tags,
			Icon:        icon,
			IsPrivate:   isPrivate,
		}
		records = append(records, record)
	}

	if len(records) > 0 {
		if err := impl.DBService.CreateInBatches(records, 100).Error; err != nil {
			printer.Error("Import bookmarks error: %v", err)
			return nil, errcode.ErrDB
		}
	}

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