"""Tests for AddonsService.connect()."""

from __future__ import annotations

import pytest

from kuberoku.exceptions import AddonNotFoundError
from kuberoku.factory import KuberokuFactory
from kuberoku.k8s import resources
from kuberoku.models import PortMapping


@pytest.fixture()
def addon_factory(app_factory: KuberokuFactory) -> KuberokuFactory:
    """Factory with a postgres addon attached."""
    app_factory.addons.create("myapp", "postgres")
    return app_factory


class TestAddonConnect:
    def test_connect_addon(self, addon_factory: KuberokuFactory) -> None:
        target = addon_factory.addons.connect("myapp", "postgres")
        assert target.kind == "addon"
        assert target.name == "postgres"
        assert target.namespace == addon_factory.namespace
        assert len(target.ports) >= 1
        assert PortMapping(port=5432, protocol="TCP") in target.ports

    def test_connect_addon_not_found(self, app_factory: KuberokuFactory) -> None:
        with pytest.raises(AddonNotFoundError):
            app_factory.addons.connect("myapp", "nonexistent")

    def test_connect_service_name(self, addon_factory: KuberokuFactory) -> None:
        """Verify service_name is the actual K8s Service name."""
        target = addon_factory.addons.connect("myapp", "postgres")
        expected = resources.safe_name(addon_factory.prefix, "addon", "myapp-postgres")
        assert target.service_name == expected
