# 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_list_empty(runner, ws):
    data = ok(runner.invoke(app, ["projects", "list", *_BASE]))
    assert data == []


def test_list_projects(runner, ws):
    _create(runner, "alpha")
    _create(runner, "beta")
    data = ok(runner.invoke(app, ["projects", "list", *_BASE]))
    names = [p["name"] for p in data]
    assert "alpha" in names
    assert "beta" in names


def test_list_sorted_alphabetically(runner, ws):
    _create(runner, "zebra")
    _create(runner, "alpha")
    data = ok(runner.invoke(app, ["projects", "list", *_BASE]))
    names = [p["name"] for p in data]
    assert names == sorted(names)


def test_list_includes_workspace_field(runner, ws):
    _create(runner, "myproject")
    data = ok(runner.invoke(app, ["projects", "list", *_BASE]))
    assert all(p["workspace"] == WS for p in data)


def test_list_project_has_id(runner, ws):
    _create(runner, "myproject")
    data = ok(runner.invoke(app, ["projects", "list", *_BASE]))
    assert all("id" in p for p in data)
    assert all(len(p["id"]) == 36 for p in data)


def test_list_project_has_body(runner, ws):
    _create(runner, "myproject")
    data = ok(runner.invoke(app, ["projects", "list", *_BASE]))
    assert all("body" in p for p in data)


def test_list_no_default_when_unset(runner, ws):
    _create(runner, "myproject")
    data = ok(runner.invoke(app, ["projects", "list", *_BASE]))
    assert all(not p["default"] for p in data)


def test_list_shows_default_after_update(runner, ws):
    _create(runner, "alpha")
    _create(runner, "beta")
    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 len(defaults) == 1
    assert defaults[0]["name"] == "beta"
