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

WS = "personal"
_BASE = ["--workspace", WS]


def _create(runner, name):
    return runner.invoke(app, ["projects", "create", name, *_BASE])


def test_update_body(runner, ws):
    _create(runner, "myproject")
    data = ok(runner.invoke(app, ["projects", "update", "myproject", "--body", "My project", *_BASE]))
    assert data["body"] == "My project"
    assert data["name"] == "myproject"


def test_update_body_persists(runner, ws):
    _create(runner, "myproject")
    runner.invoke(app, ["projects", "update", "myproject", "--body", "Persisted", *_BASE])
    data = ok(runner.invoke(app, ["projects", "list", *_BASE]))
    proj = next(p for p in data if p["name"] == "myproject")
    assert proj["body"] == "Persisted"


def test_update_set_default(runner, ws):
    _create(runner, "alpha")
    _create(runner, "beta")
    ok(runner.invoke(app, ["projects", "update", "alpha", "--set-default", *_BASE]))
    data = ok(runner.invoke(app, ["projects", "list", *_BASE]))
    defaults = [p for p in data if p["default"]]
    assert len(defaults) == 1
    assert defaults[0]["name"] == "alpha"


def test_update_set_default_reflected_in_response(runner, ws):
    _create(runner, "myproject")
    data = ok(runner.invoke(app, ["projects", "update", "myproject", "--set-default", *_BASE]))
    assert data["default"] is True
    assert data["workspace"] == WS


def test_update_set_default_can_be_changed(runner, ws):
    _create(runner, "alpha")
    _create(runner, "beta")
    ok(runner.invoke(app, ["projects", "update", "alpha", "--set-default", *_BASE]))
    ok(runner.invoke(app, ["projects", "update", "beta", "--set-default", *_BASE]))
    data = ok(runner.invoke(app, ["projects", "list", *_BASE]))
    defaults = [p for p in data if p["default"]]
    assert defaults[0]["name"] == "beta"


def test_update_body_and_set_default_together(runner, ws):
    _create(runner, "myproject")
    data = ok(runner.invoke(app, ["projects", "update", "myproject", "--body", "Desc", "--set-default", *_BASE]))
    assert data["body"] == "Desc"
    assert data["default"] is True


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


def test_update_no_flags_errors(runner, ws):
    _create(runner, "myproject")
    e = err(runner.invoke(app, ["projects", "update", "myproject", *_BASE]))
    assert e["code"] == "VALIDATION_ERROR"


def test_update_preserves_id(runner, ws):
    data_create = ok(_create(runner, "myproject"))
    original_id = data_create["id"]
    data_update = ok(runner.invoke(app, ["projects", "update", "myproject", "--body", "new", *_BASE]))
    assert data_update["id"] == original_id
