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

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


def _create(runner, title, **kwargs):
    args = ["notes", "create", "--title", title, *_BASE]
    for k, v in kwargs.items():
        args += [f"--{k}", v]
    return runner.invoke(app, args)


def test_update_note_title(runner, ws):
    _create(runner, "Old title", body="x")
    data = ok(runner.invoke(app, ["notes", "update", "Old title", "--title", "New title", *_BASE]))
    assert data["title"] == "New title"


def test_update_note_body(runner, ws):
    _create(runner, "Edit body", body="original")
    data = ok(runner.invoke(app, ["notes", "update", "Edit body", "--body", "updated", *_BASE]))
    assert data["body"] == "updated"


def test_update_note_tags(runner, ws):
    _create(runner, "Tag edit")
    data = ok(runner.invoke(app, ["notes", "update", "Tag edit", "--tags", "x,y", *_BASE]))
    assert data["tags"] == ["x", "y"]


def test_update_note_updates_updated_at(runner, ws):
    _create(runner, "Timestamps", body="v1")
    d1 = ok(runner.invoke(app, ["notes", "read", "Timestamps", *_BASE]))
    ok(runner.invoke(app, ["notes", "update", "Timestamps", "--body", "v2", *_BASE]))
    d2 = ok(runner.invoke(app, ["notes", "read", "Timestamps", *_BASE]))
    assert d2["updated_at"] >= d1["updated_at"]


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