"""Tests for apps (list) — SDK + CLI."""

from __future__ import annotations

from click.testing import CliRunner

from kuberoku.cli.main import cli
from kuberoku.factory import KuberokuFactory
from kuberoku.sdk.apps import AppsService


class TestAppsListSDK:
    """SDK-level tests for AppsService.list()."""

    def test_list_empty(self, apps_service: AppsService) -> None:
        assert apps_service.list() == []

    def test_list_one_app(self, apps_service: AppsService) -> None:
        apps_service.create("myapi")
        apps = apps_service.list()
        assert len(apps) == 1
        assert apps[0].name == "myapi"

    def test_list_multiple_sorted(self, apps_service: AppsService) -> None:
        apps_service.create("beta")
        apps_service.create("alpha")
        apps_service.create("charlie")
        names = [a.name for a in apps_service.list()]
        assert names == ["alpha", "beta", "charlie"]

    def test_list_returns_frozen(self, apps_service: AppsService) -> None:
        apps_service.create("myapi")
        apps = apps_service.list()
        assert len(apps) == 1


class TestAppsListCLI:
    """CLI-level tests for apps (list)."""

    def test_list_cli_empty(self, cli_runner: CliRunner, factory: KuberokuFactory) -> None:
        result = cli_runner.invoke(cli, ["apps"], obj={"factory": factory})
        assert result.exit_code == 0
        assert "No items" in result.output

    def test_list_cli_with_apps(self, cli_runner: CliRunner, factory: KuberokuFactory) -> None:
        factory.apps.create("myapi")
        factory.apps.create("frontend")
        result = cli_runner.invoke(cli, ["apps"], obj={"factory": factory})
        assert result.exit_code == 0
        assert "frontend" in result.output
        assert "myapi" in result.output

    def test_list_cli_json(self, cli_runner: CliRunner, factory: KuberokuFactory) -> None:
        factory.apps.create("myapi")
        result = cli_runner.invoke(cli, ["apps", "--format", "json"], obj={"factory": factory})
        assert result.exit_code == 0
        assert '"name": "myapi"' in result.output

    def test_list_cli_help(self, cli_runner: CliRunner) -> None:
        result = cli_runner.invoke(cli, ["apps", "--help"])
        assert result.exit_code == 0
        assert "Manage apps" in result.output
