"""Tests for the service layer."""
import pytest

from django_shreck.services.model_introspection import ModelIntrospectionService
from django_shreck.services.admin_url_resolver import AdminUrlResolver


class TestModelIntrospectionService:
    """Tests for ModelIntrospectionService."""

    def test_get_all_models_returns_dict(self):
        models = ModelIntrospectionService.get_all_models()
        assert isinstance(models, dict)

    def test_get_all_models_contains_user(self):
        """Django's auth User model should be auto-discovered."""
        models = ModelIntrospectionService.get_all_models()
        assert "User" in models

    def test_get_model_fields_returns_list(self):
        from django.contrib.auth.models import User

        fields = ModelIntrospectionService.get_model_fields(User)
        assert isinstance(fields, list)
        assert len(fields) > 0

    def test_get_model_fields_has_expected_keys(self):
        from django.contrib.auth.models import User

        fields = ModelIntrospectionService.get_model_fields(User)
        for field in fields:
            assert "name" in field
            assert "type" in field

    def test_get_model_fields_contains_username(self):
        from django.contrib.auth.models import User

        fields = ModelIntrospectionService.get_model_fields(User)
        field_names = [f["name"] for f in fields]
        assert "username" in field_names

    @pytest.mark.django_db
    def test_get_instance_display_data(self):
        from django.contrib.auth.models import User

        user = User.objects.create_user(username="testuser", password="testpass")
        data = ModelIntrospectionService.get_instance_display_data(user)
        assert isinstance(data, list)
        assert len(data) > 0
        # Each item should be (field_name, field_type, value_repr)
        for item in data:
            assert len(item) == 3


class TestAdminUrlResolver:
    """Tests for AdminUrlResolver."""

    @pytest.mark.django_db
    def test_get_admin_url_for_user(self):
        from django.contrib.auth.models import User

        user = User.objects.create_user(username="admintest", password="testpass")
        url = AdminUrlResolver.get_admin_url(user)
        # URL should contain the app label and model name
        assert url is not None
        assert "auth" in url
        assert "user" in url
        assert str(user.pk) in url

    def test_get_changelist_url(self):
        from django.contrib.auth.models import User

        url = AdminUrlResolver.get_changelist_url(User.objects.none())
        assert url is not None
        assert "auth" in url
        assert "user" in url

    def test_get_admin_url_for_target_with_none(self):
        url = AdminUrlResolver.get_admin_url_for_target("not a model")
        assert url is None

    def test_open_in_browser_returns_url(self):
        url = AdminUrlResolver.open_in_browser("http://example.com")
        assert url == "http://example.com"


