import pytest
from sunwaee.cli import app
from .conftest import ok, err


def test_create_workspace(runner, env):
    data = ok(runner.invoke(app, ["workspace", "create", "pro"]))
    assert data["name"] == "pro"
    assert "pro" in data["path"]


def test_create_workspace_creates_directory(runner, env, tmp_path):
    runner.invoke(app, ["workspace", "create", "pro"])
    assert (tmp_path / "workspaces" / "pro").is_dir()


def test_create_duplicate_workspace_errors(runner, env):
    runner.invoke(app, ["workspace", "create", "pro"])
    e = err(runner.invoke(app, ["workspace", "create", "pro"]))
    assert e["code"] == "ALREADY_EXISTS"


def test_list_workspaces_empty(runner, env):
    data = ok(runner.invoke(app, ["workspace", "list"]))
    assert data == []


def test_list_workspaces(runner, env):
    runner.invoke(app, ["workspace", "create", "personal"])
    runner.invoke(app, ["workspace", "create", "pro"])
    data = ok(runner.invoke(app, ["workspace", "list"]))
    names = [w["name"] for w in data]
    assert "personal" in names
    assert "pro" in names


def test_list_shows_default(runner, env):
    runner.invoke(app, ["workspace", "create", "personal"])
    runner.invoke(app, ["workspace", "create", "pro"])
    data = ok(runner.invoke(app, ["workspace", "list"]))
    defaults = [w for w in data if w["default"]]
    assert len(defaults) == 1
    assert defaults[0]["name"] == "personal"


def test_set_default_workspace(runner, env):
    runner.invoke(app, ["workspace", "create", "personal"])
    runner.invoke(app, ["workspace", "create", "pro"])
    ok(runner.invoke(app, ["workspace", "set-default", "pro"]))
    data = ok(runner.invoke(app, ["workspace", "list"]))
    defaults = [w for w in data if w["default"]]
    assert defaults[0]["name"] == "pro"


def test_set_default_nonexistent_errors(runner, env):
    e = err(runner.invoke(app, ["workspace", "set-default", "ghost"]))
    assert e["code"] == "NOT_FOUND"


def test_delete_workspace_requires_confirm(runner, env):
    runner.invoke(app, ["workspace", "create", "pro"])
    e = err(runner.invoke(app, ["workspace", "delete", "pro"]))
    assert e["code"] == "CONFIRMATION_REQUIRED"


def test_delete_workspace(runner, env, tmp_path):
    runner.invoke(app, ["workspace", "create", "pro"])
    ok(runner.invoke(app, ["workspace", "delete", "pro", "--confirm"]))
    assert not (tmp_path / "workspaces" / "pro").exists()


def test_delete_workspace_cascades_data(runner, env, tmp_path):
    runner.invoke(app, ["workspace", "create", "pro"])
    runner.invoke(app, ["note", "create", "--title", "A note", "--body", "hi", "--workspace", "pro"])
    ok(runner.invoke(app, ["workspace", "delete", "pro", "--confirm"]))
    assert not (tmp_path / "workspaces" / "pro").exists()


def test_delete_nonexistent_workspace_errors(runner, env):
    e = err(runner.invoke(app, ["workspace", "delete", "ghost", "--confirm"]))
    assert e["code"] == "NOT_FOUND"
