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

// 获取笔记详情
func GetNote(ctx context.Context, in *pb.IdentRequest) (reply *pb.CloudNoteItem, err error) {
	// parse authorization meta.
	auth, err := service.ParseMetaCtx(ctx, nil)
	if err != nil {
		return nil, err
	}

	// validate request id,identity.
	if in.Id == 0 && in.Identity == "" {
		return nil, errcode.ErrInvalidArgument
	}

	// logic code
	var note models.CloudNote
	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.Preload("Attachments").First(&note).Error; err != nil {
		printer.Error("Note not found: %v", err)
		return nil, errcode.ErrInvalidArgument
	}

	// 转换附件数据
	var attachments []*pb.NoteAttachmentItem
	for _, attachment := range note.Attachments {
		attachments = append(attachments, &pb.NoteAttachmentItem{
			Id:        uint64(attachment.ID),
			NoteId:    uint64(attachment.NoteID),
			FileName:  attachment.FileName,
			FilePath:  attachment.FilePath,
			FileSize:  attachment.FileSize,
			MimeType:  attachment.MimeType,
			CreatedAt: attachment.CreatedAt.Format(time.RFC3339),
		})
	}

	reply = &pb.CloudNoteItem{
		Id:          uint64(note.ID),
		Identity:    note.Identity,
		Title:       note.Title,
		Content:     note.Content,
		Category:    note.Category,
		Tags:        note.Tags,
		IsMarkdown:  note.IsMarkdown,
		IsPinned:    note.IsPinned,
		IsPrivate:   note.IsPrivate,
		Views:       int32(note.Views),
		CreatedAt:   note.CreatedAt.Format(time.RFC3339),
		UpdatedAt:   note.UpdatedAt.Format(time.RFC3339),
		Attachments: attachments,
	}

	return reply, nil
}
