"""Tests for the source-bucket registry resolution."""
from unittest.mock import MagicMock, patch

from django.test import SimpleTestCase, override_settings

from library.services import source_s3

_REGISTRY = {
    "daedalus": {
        "endpoint_url": "https://nyx.test:8555",
        "access_key_id": "dae_key",
        "secret_access_key": "dae_secret",
        "bucket_name": "daedalus",
        "region_name": "us-east-1",
        "use_ssl": True,
        "verify": True,
    },
    "spelunker": {
        "endpoint_url": "https://nyx.test:8555",
        "access_key_id": "spel_key",
        "secret_access_key": "spel_secret",
        "bucket_name": "spelunker",
        "region_name": "us-east-1",
        "use_ssl": True,
        "verify": True,
    },
}


@override_settings(SOURCE_S3_BUCKETS=_REGISTRY)
class SourceConfigTest(SimpleTestCase):
    def test_known_source(self):
        cfg = source_s3._source_config("spelunker")
        self.assertEqual(cfg["bucket_name"], "spelunker")
        self.assertEqual(cfg["access_key_id"], "spel_key")

    def test_unknown_source_falls_back_to_daedalus(self):
        cfg = source_s3._source_config("totally-unknown")
        self.assertEqual(cfg["bucket_name"], "daedalus")

    def test_blank_source_falls_back_to_daedalus(self):
        cfg = source_s3._source_config("")
        self.assertEqual(cfg["bucket_name"], "daedalus")

    @patch("library.services.source_s3.boto3.client")
    def test_fetch_uses_source_bucket(self, mock_boto_client):
        client = MagicMock()
        body = MagicMock()
        body.read.return_value = b"file-bytes"
        client.get_object.return_value = {"Body": body}
        mock_boto_client.return_value = client

        data = source_s3.fetch_from_source("spelunker", "3/readme.md")

        self.assertEqual(data, b"file-bytes")
        client.get_object.assert_called_once_with(
            Bucket="spelunker", Key="3/readme.md"
        )
        # boto client built with the spelunker source credentials
        _, kwargs = mock_boto_client.call_args
        self.assertEqual(kwargs["aws_access_key_id"], "spel_key")
