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

// 搜索笔记
func SearchNotes(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

	// 构建搜索查询
	query := impl.DBService.Model(&models.CloudNote{}).Where("passport_id = ?", auth.ID)

	// 添加搜索条件
	if keyword, exists := in.Params["keyword"]; exists && keyword != "" {
		searchKeyword := "%" + strings.ToLower(keyword) + "%"
		query = query.Where("LOWER(title) LIKE ? OR LOWER(content) LIKE ? OR LOWER(tags) LIKE ?", searchKeyword, searchKeyword, searchKeyword)
	}

	// 获取总数
	if err := query.Count(&total).Error; err != nil {
		return nil, err
	}

	// 分页查询
	offset := (in.PageNo - 1) * in.PageSize
	if err := query.
		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
}
