"""Tests for ReleasesService.prune."""

from __future__ import annotations

from kuberoku.factory import KuberokuFactory
from kuberoku.models import ProcessFormation


def _create_releases(factory: KuberokuFactory, count: int) -> None:
    formation = {"web": ProcessFormation(1, None, "default")}
    for i in range(1, count + 1):
        factory.releases.create_release(
            "myapp", images={"web": f"v{i}"}, formation=formation, description=f"Release v{i}"
        )


def test_prune_keeps_n(app_factory: KuberokuFactory) -> None:
    _create_releases(app_factory, 10)
    deleted = app_factory.releases.prune("myapp", keep=5)
    assert deleted == 5
    remaining = app_factory.releases.list("myapp", num=100)
    assert len(remaining) == 5
    # Should keep newest
    versions = [r.version for r in remaining]
    assert versions == [10, 9, 8, 7, 6]


def test_prune_nothing_to_delete(app_factory: KuberokuFactory) -> None:
    _create_releases(app_factory, 3)
    deleted = app_factory.releases.prune("myapp", keep=5)
    assert deleted == 0


def test_prune_returns_count(app_factory: KuberokuFactory) -> None:
    _create_releases(app_factory, 8)
    deleted = app_factory.releases.prune("myapp", keep=3)
    assert deleted == 5


def test_prune_on_step(app_factory: KuberokuFactory) -> None:
    _create_releases(app_factory, 5)
    steps: list[str] = []
    app_factory.releases.prune("myapp", keep=2, on_step=steps.append)
    assert any("Pruned" in s for s in steps)
