package converter

import (
	"strings"
	"time"

	"github.com/tidbcloud/AgentTeam/internal/api/dto"
	"github.com/tidbcloud/AgentTeam/internal/store/message"
)

type ChannelAttachmentCursorEncoder func(message.ChannelAttachmentCursor) string

func ToChannelAttachmentPage(page message.ChannelAttachmentPage, encodeCursor ChannelAttachmentCursorEncoder) dto.ChannelAttachmentPage {
	items := make([]dto.ChannelAttachmentItem, 0, len(page.Items))
	for _, item := range page.Items {
		items = append(items, ToChannelAttachmentItem(item))
	}
	nextCursor := ""
	if page.HasMore && encodeCursor != nil {
		nextCursor = encodeCursor(page.NextCursor)
	}
	return dto.ChannelAttachmentPage{Items: items, HasMore: page.HasMore, NextCursor: nextCursor}
}

func ToChannelAttachmentItem(item message.ChannelAttachmentItem) dto.ChannelAttachmentItem {
	return dto.ChannelAttachmentItem{
		ID:         strings.TrimSpace(item.ID),
		Kind:       strings.TrimSpace(string(item.Kind)),
		Title:      strings.TrimSpace(item.Title),
		CreatedAt:  formatChannelAttachmentTime(item.CreatedAt),
		Author:     ToAuthorProfile(item.Author),
		Message:    ToChannelAttachmentMessageLocation(item.Message),
		Snippet:    strings.TrimSpace(item.Snippet),
		Attachment: ToChannelAttachmentDetail(item.Attachment),
	}
}

func ToChannelAttachmentMessageLocation(location message.ChannelAttachmentMessageLocation) dto.ChannelAttachmentMessageLocation {
	return dto.ChannelAttachmentMessageLocation{
		MessageID:           strings.TrimSpace(location.MessageID),
		ScopeID:             strings.TrimSpace(location.ScopeID),
		ScopeType:           strings.TrimSpace(location.ScopeType),
		ParentChannelID:     strings.TrimSpace(location.ParentChannelID),
		ThreadChannelID:     strings.TrimSpace(location.ThreadChannelID),
		ThreadRootMessageID: strings.TrimSpace(location.ThreadRootMessageID),
		ThreadTitle:         strings.TrimSpace(location.ThreadTitle),
	}
}

func ToChannelAttachmentDetail(attachment *message.ChannelAttachmentDetail) *dto.ChannelAttachmentDetail {
	if attachment == nil {
		return nil
	}
	return &dto.ChannelAttachmentDetail{
		ID:           strings.TrimSpace(attachment.ID),
		Filename:     strings.TrimSpace(attachment.Filename),
		ContentType:  strings.TrimSpace(attachment.ContentType),
		SizeBytes:    attachment.SizeBytes,
		ThumbnailURL: strings.TrimSpace(attachment.ThumbnailURL),
	}
}

func formatChannelAttachmentTime(value time.Time) string {
	if value.IsZero() {
		return ""
	}
	return value.UTC().Format(time.RFC3339Nano)
}
