"""Tests for sources app models."""

import pytest
from django.db import IntegrityError

from .factories import SourceFactory


@pytest.mark.django_db
class TestSource:
    """Tests for the Source model."""

    def test_create_source(self):
        """Test creating a source with the factory."""
        source = SourceFactory()
        assert source.pk is not None
        assert source.name.startswith("Source")
        assert source.workspace is not None

    def test_source_str(self):
        """Test source string representation."""
        source = SourceFactory(kind="github_repo", name="my-project")
        assert str(source) == "github_repo:my-project"

    def test_source_kind_choices(self):
        """Test source with different kind choices."""
        kinds = [
            "slack_channel",
            "discord_channel",
            "github_repo",
            "discourse_category",
            "twitter_stream",
        ]
        for kind in kinds:
            source = SourceFactory(kind=kind)
            assert source.kind == kind

    def test_source_unique_kind_external_id(self):
        """Test that kind + external_id must be unique."""
        SourceFactory(kind="github_repo", external_id="repo-123")
        with pytest.raises(IntegrityError):
            SourceFactory(kind="github_repo", external_id="repo-123")

    def test_source_same_external_id_different_kind(self):
        """Test same external_id with different kind is allowed."""
        SourceFactory(kind="github_repo", external_id="123")
        source2 = SourceFactory(kind="slack_channel", external_id="123")
        assert source2.pk is not None

    def test_source_with_metadata(self):
        """Test source with custom metadata."""
        metadata = {"owner": "acme", "private": True}
        source = SourceFactory(metadata=metadata)
        assert source.metadata == metadata

    def test_source_default_metadata(self):
        """Test source has empty dict as default metadata."""
        source = SourceFactory()
        assert source.metadata == {}

    def test_source_has_timestamps(self):
        """Test that source has created_at and updated_at."""
        source = SourceFactory()
        assert source.created_at is not None
        assert source.updated_at is not None

    def test_source_belongs_to_workspace(self):
        """Test source belongs to a workspace."""
        source = SourceFactory()
        assert source.workspace is not None
        assert source in source.workspace.sources.all()
