package server

import (
	"bytes"
	"context"
	"io"
	"os"
	"path/filepath"
	"testing"
	"time"

	"github.com/stretchr/testify/require"
	"github.com/tidbcloud/AgentTeam/internal/config"
	"github.com/tidbcloud/AgentTeam/internal/contentpayload"
	"github.com/tidbcloud/AgentTeam/internal/store/content"
	"gorm.io/driver/sqlite"
	"gorm.io/gorm"
)

func TestDisabledContentStoreRuntimeDoesNotOpenPayloadRoot(t *testing.T) {
	root := filepath.Join(t.TempDir(), "not-created")
	runtime, err := newContentStoreRuntime(config.ContentStoreConfig{FilesystemRoot: root}, nil, nil)
	require.NoError(t, err)
	require.Nil(t, runtime.payload)
	require.Nil(t, runtime.store)
	require.Nil(t, runtime.role)
	require.Nil(t, runtime.skill)
	require.Nil(t, runtime.kb)
	require.Nil(t, runtime.memory)
	require.Nil(t, runtime.automation)
	_, err = os.Stat(root)
	require.ErrorIs(t, err, os.ErrNotExist)
}

func TestDisabledContentStoreRuntimeRejectsPersistedNativeKBSource(t *testing.T) {
	db, err := gorm.Open(sqlite.Open("file:"+t.Name()+"?mode=memory&cache=shared"), &gorm.Config{})
	require.NoError(t, err)
	require.NoError(t, db.AutoMigrate(&content.Authority{}))
	now := time.Now().UTC()
	require.NoError(t, db.Create(&content.Authority{
		ID: "cta_native", WorkspaceID: "wsp_1", Domain: "kb_source", BindingKey: "src_1",
		State: content.AuthorityStateNativeActive, Generation: 1, Checkpoint: "kb1|ctv_1|", UpdatedBy: "owner",
		CreatedAt: now, UpdatedAt: now,
	}).Error)

	runtime, err := newContentStoreRuntime(config.ContentStoreConfig{}, db, nil)
	require.ErrorContains(t, err, "cannot be disabled")
	require.Nil(t, runtime.store)
}

func TestContentTreePayloadPersistsAcrossRestart(t *testing.T) {
	root := t.TempDir()
	first, err := openContentTreePayload(root)
	require.NoError(t, err)
	staged, err := first.StageTree(context.Background(), contentpayload.StageTreeRequest{
		WorkspaceID: "wsp_1", ContentID: "ctn_1", VersionID: "ctv_1", Actor: "test",
		Files: []contentpayload.File{{Path: "SKILL.md", Size: 5, Content: bytes.NewBufferString("hello")}},
	})
	require.NoError(t, err)
	require.Contains(t, string(staged.ManifestRef), "@")
	require.NoError(t, first.Close())

	second, err := openContentTreePayload(root)
	require.NoError(t, err)
	t.Cleanup(func() { require.NoError(t, second.Close()) })
	body, _, err := second.OpenFile(context.Background(), staged.ManifestRef, "SKILL.md", nil)
	require.NoError(t, err)
	data, err := io.ReadAll(body)
	require.NoError(t, err)
	require.NoError(t, body.Close())
	require.Equal(t, "hello", string(data))
}
