package message

import (
	"context"
	"fmt"
	"testing"
	"time"

	"github.com/stretchr/testify/require"

	"github.com/tidbcloud/AgentTeam/internal/archive"
	"github.com/tidbcloud/AgentTeam/internal/coredb"
	"github.com/tidbcloud/AgentTeam/internal/store/testfixture"
)

func TestReadThreadHistoryRecordsFromColdIncludesMessageID(t *testing.T) {
	t.Parallel()

	ctx := context.Background()
	pool := startMessagingTestPool(t, ctx)

	archiveStorage, err := archive.NewFilesystem(t.TempDir())
	require.NoError(t, err)

	dataStore := New(pool, archiveStorage, 30, Options{})

	now := time.Now().UTC()
	workspaceID := "wsp_history_cold"
	channelID := "chn_history_cold"

	mustExecMessaging(t, ctx, pool, `
INSERT INTO workspaces (id, organization_id, slug, name, latest_message_seq, created_at, updated_at)
VALUES ($1, $2, 'history-cold', 'history-cold', 0, $3, $3)
`, workspaceID, testfixture.SeedWorkspaceOrganization(t, ctx, pool, workspaceID, now), now)
	insertColdHistoryScope(t, ctx, pool, workspaceID, channelID, "channel:history-cold", now)

	base := now.Add(-time.Hour)
	archiveChunk := make([]archive.Message, 0, archive.ChunkMessageCount)
	for seq := int64(1); seq <= archive.ChunkMessageCount; seq++ {
		archiveChunk = append(archiveChunk, archive.Message{
			ID:         fmt.Sprintf("msg_%d", seq),
			Seq:        seq,
			SenderType: "agent",
			SenderName: "mem_sender",
			Content:    fmt.Sprintf("message %d", seq),
			Metadata: map[string]any{
				"app_event_type": "archived.test",
				"seq":            seq,
			},
			Timestamp: base.Add(time.Duration(seq) * time.Second),
		})
	}
	require.NoError(t, archiveStorage.WriteChunk(ctx, workspaceID, channelID, 1, archiveChunk))

	after := int64(0)
	records, hasMore, err := dataStore.ReadThreadHistoryRecords(ctx, workspaceID, channelID, 3, nil, &after)
	require.NoError(t, err)
	require.True(t, hasMore)
	require.Len(t, records, 3)
	require.EqualValues(t, 1, records[0].Seq)
	require.Equal(t, "msg_1", records[0].MessageID)
	require.Equal(t, "archived.test", records[0].Metadata["app_event_type"])
}

func insertColdHistoryScope(t *testing.T, ctx context.Context, pool coredb.QueryExecer, workspaceID string, scopeID string, identityKey string, now time.Time) {
	t.Helper()

	mustExecMessaging(t, ctx, pool, `
INSERT INTO scopes (
	id, workspace_id, type, identity_key,
	latest_seq, latest_global_seq, archived_until_seq,
	status, created_at, updated_at
) VALUES (
	$1, $2, 'channel', $3,
	1000, 1000, 1000,
	'active', $4, $4
)
`, scopeID, workspaceID, identityKey, now)
}
