"""Tests for PsService.scale."""

from __future__ import annotations

import pytest

from kuberoku.exceptions import ProcessTypeNotFoundError
from kuberoku.factory import KuberokuFactory
from kuberoku.k8s.resources import safe_name


def test_scale_up(deployed_factory: KuberokuFactory) -> None:
    result = deployed_factory.ps.scale("myapp", {"web": 3})
    assert result["web"].replicas == 3
    dep = deployed_factory.k8s.get_deployment(
        deployed_factory.namespace, safe_name(deployed_factory.prefix, "myapp", "web")
    )
    assert dep["spec"]["replicas"] == 3


def test_scale_down(deployed_factory: KuberokuFactory) -> None:
    deployed_factory.ps.scale("myapp", {"web": 5})
    result = deployed_factory.ps.scale("myapp", {"web": 2})
    assert result["web"].replicas == 2


def test_scale_multiple_types(deployed_factory: KuberokuFactory) -> None:
    deployed_factory.deploy.deploy("myapp", image="myapp:v1", process_type="worker", wait=False)
    result = deployed_factory.ps.scale("myapp", {"web": 3, "worker": 2})
    assert result["web"].replicas == 3
    assert result["worker"].replicas == 2


def test_scale_creates_release(deployed_factory: KuberokuFactory) -> None:
    deployed_factory.ps.scale("myapp", {"web": 3})
    releases = deployed_factory.releases.list("myapp")
    assert any("Scale" in r.description for r in releases)


def test_scale_type_not_found(deployed_factory: KuberokuFactory) -> None:
    with pytest.raises(ProcessTypeNotFoundError):
        deployed_factory.ps.scale("myapp", {"nonexistent": 3})


def test_scale_on_step(deployed_factory: KuberokuFactory) -> None:
    steps: list[str] = []
    deployed_factory.ps.scale("myapp", {"web": 3}, on_step=steps.append)
    assert any("Scaled" in s for s in steps)
