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

// 获取笔记列表
func ListNotes(ctx context.Context, in *pb.FetchRequest) (reply *pb.ListNotesResponse, 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 notes []models.CloudNote
	var total int64

	// 获取总数
	if err := impl.DBService.Model(&models.CloudNote{}).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).
		Preload("Attachments").
		Order("is_pinned DESC, created_at DESC").
		Offset(int(offset)).
		Limit(int(in.PageSize)).
		Find(&notes).Error; err != nil {
		return nil, err
	}

	// 转换数据
	var noteItems []*pb.CloudNoteItem
	for _, note := range notes {
		// 转换附件数据
		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),
			})
		}

		noteItems = append(noteItems, &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,
		})
	}

	reply = &pb.ListNotesResponse{
		Notes: noteItems,
		Total: total,
	}

	return reply, nil
}
