package note

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

// 上传附件
func InsertAttachment(ctx context.Context, in *pb.NoteAttachmentItem) (reply *pb.StatusReply, err error) {
	// parse authorization meta.
	auth, err := service.ParseMetaCtx(ctx, nil)
	if err != nil {
		return nil, err
	}

	// validate request
	if in.NoteId == 0 {
		return nil, errcode.ErrInvalidArgument
	}
	if strings.TrimSpace(in.FileName) == "" {
		return nil, errcode.ErrInvalidArgument
	}
	if strings.TrimSpace(in.FilePath) == "" {
		return nil, errcode.ErrInvalidArgument
	}

	// logic code
	// 验证笔记是否存在且属于当前用户
	var note models.CloudNote
	if err := impl.DBService.Where("id = ? AND passport_id = ?", in.NoteId, auth.ID).First(&note).Error; err != nil {
		printer.Error("Note not found: %v", err)
		return nil, errcode.ErrInvalidArgument
	}

	// 创建附件记录
	attachment := models.NoteAttachment{
		NoteID:    uint(in.NoteId),
		FileName:  in.FileName,
		FilePath:  in.FilePath,
		FileSize:  in.FileSize,
		MimeType:  in.MimeType,
		CreatedAt: time.Now(),
	}

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

	return &pb.StatusReply{
		Details: string(rune(attachment.ID)),
		Timeseq: time.Now().UnixMilli(),
	}, nil
}
