"""Tests for domains:clear."""

from __future__ import annotations

from typing import Any

import pytest

from kuberoku.exceptions import AppNotFoundError
from kuberoku.factory import KuberokuFactory
from kuberoku.k8s import resources
from tests.backends.fake import FakeNotFoundError


class TestDomainsClear:
    def test_clear_removes_all(
        self, factory: KuberokuFactory, k8s: Any, app_with_web: str
    ) -> None:
        factory.domains.add(app_with_web, "api.example.com")
        factory.domains.add(app_with_web, "auto.example.com", auto_generated=True)
        factory.domains.clear(app_with_web)

        ingress_name = resources.safe_name(factory.prefix, "ingress", app_with_web)
        with pytest.raises(FakeNotFoundError):
            k8s.get_ingress(factory.namespace, ingress_name)

    def test_clear_no_ingress_is_noop(self, factory: KuberokuFactory, app_with_web: str) -> None:
        # Should not raise
        factory.domains.clear(app_with_web)

    def test_clear_nonexistent_app_raises(self, factory: KuberokuFactory) -> None:
        with pytest.raises(AppNotFoundError):
            factory.domains.clear("nonexistent")

    def test_clear_on_step_callback(self, factory: KuberokuFactory, app_with_web: str) -> None:
        factory.domains.add(app_with_web, "api.example.com")
        steps: list[str] = []
        factory.domains.clear(app_with_web, on_step=steps.append)
        assert len(steps) > 0

    def test_clear_removes_external_policy_owner(
        self, factory: KuberokuFactory, k8s: Any, app_with_web: str
    ) -> None:
        """When domains is the only owner, policy is deleted."""
        factory.domains.add(app_with_web, "api.example.com")
        factory.domains.clear(app_with_web)

        np_name = resources.safe_name(factory.prefix, "netpol-external", f"{app_with_web}-web")
        with pytest.raises(FakeNotFoundError):
            k8s.get_network_policy(factory.namespace, np_name)
