# standard
# third party
# custom
from ...conftest import ok, err
from sunwaee.cli import app


def test_update_body(runner, env):
    runner.invoke(app, ["workspaces", "create", "personal"])
    data = ok(runner.invoke(app, ["workspaces", "update", "personal", "--body", "My workspace"]))
    assert data["body"] == "My workspace"
    assert data["name"] == "personal"


def test_update_body_persists(runner, env):
    runner.invoke(app, ["workspaces", "create", "personal"])
    runner.invoke(app, ["workspaces", "update", "personal", "--body", "Persisted"])
    data = ok(runner.invoke(app, ["workspaces", "list"]))
    ws = next(w for w in data if w["name"] == "personal")
    assert ws["body"] == "Persisted"


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


def test_update_set_default_reflected_in_response(runner, env):
    runner.invoke(app, ["workspaces", "create", "personal"])
    runner.invoke(app, ["workspaces", "create", "pro"])
    data = ok(runner.invoke(app, ["workspaces", "update", "pro", "--set-default"]))
    assert data["default"] is True


def test_update_body_and_set_default_together(runner, env):
    runner.invoke(app, ["workspaces", "create", "personal"])
    runner.invoke(app, ["workspaces", "create", "pro"])
    data = ok(runner.invoke(app, ["workspaces", "update", "pro", "--body", "Work", "--set-default"]))
    assert data["body"] == "Work"
    assert data["default"] is True


def test_update_nonexistent_errors(runner, env):
    e = err(runner.invoke(app, ["workspaces", "update", "ghost", "--body", "x"]))
    assert e["code"] == "NOT_FOUND"


def test_update_no_flags_errors(runner, env):
    runner.invoke(app, ["workspaces", "create", "personal"])
    e = err(runner.invoke(app, ["workspaces", "update", "personal"]))
    assert e["code"] == "VALIDATION_ERROR"


def test_update_preserves_id(runner, env):
    data_create = ok(runner.invoke(app, ["workspaces", "create", "personal"]))
    original_id = data_create["id"]
    data_update = ok(runner.invoke(app, ["workspaces", "update", "personal", "--body", "new"]))
    assert data_update["id"] == original_id
