package jupyter_test

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

	"github.com/jfraeys/fetch_ml/internal/jupyter"
)

func TestTrashAndRestoreWorkspace(t *testing.T) {
	tmp := t.TempDir()
	state := filepath.Join(tmp, "state")
	workspaces := filepath.Join(tmp, "workspaces")
	trash := filepath.Join(tmp, "trash")

	oldState := os.Getenv("FETCHML_JUPYTER_STATE_DIR")
	oldWS := os.Getenv("FETCHML_JUPYTER_WORKSPACE_BASE")
	oldTrash := os.Getenv("FETCHML_JUPYTER_TRASH_DIR")
	t.Cleanup(func() {
		_ = os.Setenv("FETCHML_JUPYTER_STATE_DIR", oldState)
		_ = os.Setenv("FETCHML_JUPYTER_WORKSPACE_BASE", oldWS)
		_ = os.Setenv("FETCHML_JUPYTER_TRASH_DIR", oldTrash)
	})
	_ = os.Setenv("FETCHML_JUPYTER_STATE_DIR", state)
	_ = os.Setenv("FETCHML_JUPYTER_WORKSPACE_BASE", workspaces)
	_ = os.Setenv("FETCHML_JUPYTER_TRASH_DIR", trash)

	wsName := "my-workspace"
	wsPath := filepath.Join(workspaces, wsName)
	if err := os.MkdirAll(wsPath, 0o750); err != nil {
		t.Fatalf("mkdir workspace: %v", err)
	}
	if err := os.WriteFile(filepath.Join(wsPath, "note.txt"), []byte("hello"), 0o600); err != nil {
		t.Fatalf("write file: %v", err)
	}

	trashPath, err := jupyter.MoveWorkspaceToTrash(wsPath, wsName)
	if err != nil {
		t.Fatalf("MoveWorkspaceToTrash: %v", err)
	}
	if _, err := os.Stat(trashPath); err != nil {
		t.Fatalf("expected trashed dir to exist: %v", err)
	}
	if _, err := os.Stat(wsPath); !os.IsNotExist(err) {
		t.Fatalf("expected original workspace to be moved, stat err=%v", err)
	}

	restored, err := jupyter.RestoreWorkspace(context.Background(), wsName)
	if err != nil {
		t.Fatalf("RestoreWorkspace: %v", err)
	}
	if restored != wsPath {
		t.Fatalf("expected restored path %q, got %q", wsPath, restored)
	}
	if _, err := os.Stat(filepath.Join(wsPath, "note.txt")); err != nil {
		t.Fatalf("expected restored file to exist: %v", err)
	}
}
