package file

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

	"github.com/enmanuel/agents/internal/config"
)

func TestDeleteFile_DeletesExistingFile(t *testing.T) {
	tmp := t.TempDir()
	target := filepath.Join(tmp, "doomed.txt")
	os.WriteFile(target, []byte("bye"), 0644)

	cfg := config.FileOpsCfg{AllowedPaths: []string{tmp}, ReadOnly: false}
	tool := NewDeleteFile(cfg)

	result := tool.Exec(context.Background(), map[string]any{"path": target})
	if result.Err != nil {
		t.Fatalf("expected success, got: %v", result.Err)
	}

	if _, err := os.Stat(target); !os.IsNotExist(err) {
		t.Fatal("file should have been deleted")
	}

	if !strings.Contains(result.Output, "deleted") {
		t.Fatalf("expected 'deleted' in output, got: %q", result.Output)
	}
}

func TestDeleteFile_RejectsDirectories(t *testing.T) {
	tmp := t.TempDir()
	subdir := filepath.Join(tmp, "mydir")
	os.Mkdir(subdir, 0755)

	cfg := config.FileOpsCfg{AllowedPaths: []string{tmp}, ReadOnly: false}
	tool := NewDeleteFile(cfg)

	result := tool.Exec(context.Background(), map[string]any{"path": subdir})
	if result.Err == nil {
		t.Fatal("expected error when trying to delete a directory")
	}
	if !strings.Contains(result.Err.Error(), "directory") {
		t.Fatalf("expected directory error, got: %v", result.Err)
	}

	// Verify directory still exists
	if _, err := os.Stat(subdir); os.IsNotExist(err) {
		t.Fatal("directory should not have been deleted")
	}
}

func TestDeleteFile_RejectsReadOnly(t *testing.T) {
	tmp := t.TempDir()
	target := filepath.Join(tmp, "protected.txt")
	os.WriteFile(target, []byte("safe"), 0644)

	cfg := config.FileOpsCfg{AllowedPaths: []string{tmp}, ReadOnly: true}
	tool := NewDeleteFile(cfg)

	result := tool.Exec(context.Background(), map[string]any{"path": target})
	if result.Err == nil {
		t.Fatal("expected error when ReadOnly is true")
	}
	if !strings.Contains(result.Err.Error(), "read_only") {
		t.Fatalf("expected read_only error, got: %v", result.Err)
	}

	// Verify file still exists
	if _, err := os.Stat(target); os.IsNotExist(err) {
		t.Fatal("file should not have been deleted")
	}
}

func TestDeleteFile_RejectsPathOutsideAllowed(t *testing.T) {
	tmp := t.TempDir()
	cfg := config.FileOpsCfg{AllowedPaths: []string{tmp}, ReadOnly: false}
	tool := NewDeleteFile(cfg)

	result := tool.Exec(context.Background(), map[string]any{"path": "/etc/hosts"})
	if result.Err == nil {
		t.Fatal("expected error for path outside allowed")
	}
}

func TestDeleteFile_PathTraversal(t *testing.T) {
	tmp := t.TempDir()
	cfg := config.FileOpsCfg{AllowedPaths: []string{tmp}, ReadOnly: false}
	tool := NewDeleteFile(cfg)

	result := tool.Exec(context.Background(), map[string]any{
		"path": filepath.Join(tmp, "..", "..", "etc", "hosts"),
	})
	if result.Err == nil {
		t.Fatal("expected error for path traversal")
	}
}

func TestDeleteFile_SymlinkEscape(t *testing.T) {
	tmp := t.TempDir()

	// Create a file outside allowed paths
	outside := t.TempDir()
	outsideFile := filepath.Join(outside, "secret.txt")
	os.WriteFile(outsideFile, []byte("secret"), 0644)

	// Create symlink inside allowed paths pointing to the outside file
	link := filepath.Join(tmp, "link.txt")
	os.Symlink(outsideFile, link)

	cfg := config.FileOpsCfg{AllowedPaths: []string{tmp}, ReadOnly: false}
	tool := NewDeleteFile(cfg)

	result := tool.Exec(context.Background(), map[string]any{"path": link})
	if result.Err == nil {
		t.Fatal("expected error for symlink escape")
	}

	// Verify the outside file still exists
	if _, err := os.Stat(outsideFile); os.IsNotExist(err) {
		t.Fatal("outside file should not have been deleted")
	}
}

func TestDeleteFile_NonExistentFile(t *testing.T) {
	tmp := t.TempDir()
	cfg := config.FileOpsCfg{AllowedPaths: []string{tmp}, ReadOnly: false}
	tool := NewDeleteFile(cfg)

	result := tool.Exec(context.Background(), map[string]any{
		"path": filepath.Join(tmp, "nonexistent.txt"),
	})
	if result.Err == nil {
		t.Fatal("expected error for non-existent file")
	}
}

func TestDeleteFile_EmptyPath(t *testing.T) {
	cfg := config.FileOpsCfg{AllowedPaths: []string{"/tmp"}, ReadOnly: false}
	tool := NewDeleteFile(cfg)

	result := tool.Exec(context.Background(), map[string]any{"path": ""})
	if result.Err == nil {
		t.Fatal("expected error for empty path")
	}
}

func TestDeleteFile_DenyByDefault(t *testing.T) {
	cfg := config.FileOpsCfg{AllowedPaths: []string{}, ReadOnly: false}
	tool := NewDeleteFile(cfg)

	result := tool.Exec(context.Background(), map[string]any{"path": "/tmp/test.txt"})
	if result.Err == nil {
		t.Fatal("expected error when AllowedPaths is empty")
	}
}
