package handlers_test

import (
	"context"
	"os"
	"path/filepath"
	"testing"

	"github.com/google/uuid"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"

	"github.com/yan1h/agent-coding-workflow/internal/acp/handlers"
)

func TestFsWrite_HappyPath(t *testing.T) {
	t.Parallel()
	tmp := t.TempDir()
	h := handlers.NewFsWriteHandler()
	sess := handlers.SessionContext{SessionID: uuid.New(), CwdPath: tmp}

	target := filepath.Join(tmp, "newdir", "x.txt")
	params := mustJSON(t, map[string]any{
		"sessionId": "x", "path": target, "content": "hello",
	})
	res := h.Handle(context.Background(), sess, params)
	require.Nil(t, res.Err)

	got, err := os.ReadFile(target)
	require.NoError(t, err)
	assert.Equal(t, "hello", string(got))
}

func TestFsWrite_OutsideWorktree(t *testing.T) {
	t.Parallel()
	tmp := t.TempDir()
	h := handlers.NewFsWriteHandler()
	sess := handlers.SessionContext{CwdPath: tmp}

	outside := filepath.Join(filepath.VolumeName(tmp)+string(filepath.Separator), "tmp", "escape.txt")
	params := mustJSON(t, map[string]any{
		"sessionId": "x", "path": outside, "content": "evil",
	})
	res := h.Handle(context.Background(), sess, params)
	require.NotNil(t, res.Err)
	assert.Equal(t, -32001, res.Err.Code)
}

// 父目录是 worktree 内指向外部的 symlink、目标文件不存在 → 必须被拒，
// 且外部目录不能出现新建文件（防 symlink 逃逸写出 worktree）。
func TestFsWrite_SymlinkDirEscape(t *testing.T) {
	t.Parallel()
	tmp := t.TempDir()
	outside := t.TempDir()

	link := filepath.Join(tmp, "link-dir")
	if err := os.Symlink(outside, link); err != nil {
		t.Skipf("symlink not supported on this platform: %v", err)
	}

	h := handlers.NewFsWriteHandler()
	sess := handlers.SessionContext{CwdPath: tmp}
	params := mustJSON(t, map[string]any{
		"sessionId": "x", "path": filepath.Join(link, "escape.txt"), "content": "evil",
	})
	res := h.Handle(context.Background(), sess, params)
	require.NotNil(t, res.Err)
	assert.Equal(t, -32001, res.Err.Code)

	_, statErr := os.Stat(filepath.Join(outside, "escape.txt"))
	assert.True(t, os.IsNotExist(statErr), "外部目录不应被写入")
}
