"""Contract tests: Namespace operations.

These tests run identically on FakeK8sClient and the real K8s cluster,
proving the fake matches real K8s behavior for Namespace operations.

Note: These tests use their own namespace names (not tmp_namespace)
since they test namespace creation/existence directly.
"""

from __future__ import annotations

import contextlib
import uuid

import pytest

from tests.backends.fake import FakeConflictError


class TestNamespaceCRUD:
    """Namespace create / exists contract."""

    def test_create_and_exists(self, k8s_client, tmp_namespace, request):
        # Use k8ut- prefix so session cleanup can find it
        ns = f"k8ut-ns-{uuid.uuid4().hex[:10]}"
        k8s_client.create_namespace(ns)

        def _cleanup() -> None:
            with contextlib.suppress(Exception):
                k8s_client.delete_namespace(ns)

        request.addfinalizer(_cleanup)
        assert k8s_client.namespace_exists(ns) is True

    def test_namespace_not_exists(self, k8s_client, tmp_namespace):
        assert k8s_client.namespace_exists(f"no-such-ns-{uuid.uuid4().hex[:10]}") is False

    def test_create_already_exists(self, k8s_client, tmp_namespace, request):
        ns = f"k8ut-dup-{uuid.uuid4().hex[:10]}"
        k8s_client.create_namespace(ns)

        def _cleanup() -> None:
            with contextlib.suppress(Exception):
                k8s_client.delete_namespace(ns)

        request.addfinalizer(_cleanup)
        with pytest.raises(FakeConflictError):
            k8s_client.create_namespace(ns)
