"""Tests for ServicesService.resolve_connect() (process connect)."""

from __future__ import annotations

import pytest

from kuberoku.exceptions import (
    AppNotFoundError,
    NameNotFoundError,
)
from kuberoku.factory import KuberokuFactory
from kuberoku.k8s import resources
from kuberoku.models import PortMapping


class TestResolveConnect:
    def test_connect_process(self, deployed_factory: KuberokuFactory) -> None:
        target = deployed_factory.services.resolve_connect("myapp", "web")
        assert target.name == "web"
        assert target.app == "myapp"
        assert target.kind == "process"
        assert target.namespace == deployed_factory.namespace
        assert len(target.ports) >= 1
        assert PortMapping(port=8080, protocol="TCP") in target.ports

    def test_connect_multi_port(self, deployed_factory: KuberokuFactory) -> None:
        """Service with multiple ports returns all."""
        deployed_factory.services.add_port("myapp", "9090/tcp")
        target = deployed_factory.services.resolve_connect("myapp", "web")
        assert len(target.ports) == 2

    def test_connect_name_not_found(
        self,
        deployed_factory: KuberokuFactory,
    ) -> None:
        with pytest.raises(NameNotFoundError):
            deployed_factory.services.resolve_connect("myapp", "nonexistent")

    def test_connect_app_not_found(self, app_factory: KuberokuFactory) -> None:
        with pytest.raises(AppNotFoundError):
            app_factory.services.resolve_connect("nonexistent", "web")

    def test_connect_process_in_full_app(
        self,
        full_factory: KuberokuFactory,
    ) -> None:
        target = full_factory.services.resolve_connect("myapp", "web")
        assert target.kind == "process"

    def test_connect_service_name(
        self,
        deployed_factory: KuberokuFactory,
    ) -> None:
        """Verify service_name is the actual K8s Service name."""
        target = deployed_factory.services.resolve_connect("myapp", "web")
        expected = resources.safe_name(deployed_factory.prefix, "myapp", "web")
        assert target.service_name == expected
