from __future__ import annotations

from pathlib import Path
import sys
import unittest


ROOT = Path(__file__).parents[1]
sys.path.insert(0, str(ROOT / "tools"))
from fetch_sources import _archive_url, _request


class FetchSourcesAuthenticationTest(unittest.TestCase):
    def test_same_origin_request_carries_forgejo_token(self) -> None:
        request = _request(
            "https://forgejo.coulomb.social/api/v1/repos/coulomb/policy-nexus",
            token="test-secret",
            token_origin="https://forgejo.coulomb.social",
        )

        self.assertEqual("token test-secret", request.get_header("Authorization"))
        self.assertNotIn("test-secret", request.full_url)

    def test_cross_origin_request_refuses_source_token(self) -> None:
        with self.assertRaisesRegex(ValueError, "refusing to send source credential"):
            _request(
                "https://example.invalid/coulomb/policy-nexus/archive/main.tar.gz",
                token="test-secret",
                token_origin="https://forgejo.coulomb.social",
            )

    def test_token_and_origin_must_be_configured_together(self) -> None:
        with self.assertRaisesRegex(ValueError, "must be provided together"):
            _request(
                "https://forgejo.coulomb.social/coulomb/policy-nexus",
                token="test-secret",
            )

    def test_anonymous_request_has_no_authorization_header(self) -> None:
        request = _request("https://forgejo.coulomb.social/public/repository")

        self.assertIsNone(request.get_header("Authorization"))

    def test_archive_uses_full_resolved_revision(self) -> None:
        revision = "a" * 40

        self.assertEqual(
            f"https://forgejo.coulomb.social/coulomb/policy-nexus/archive/{revision}.tar.gz",
            _archive_url(
                "https://forgejo.coulomb.social/coulomb/policy-nexus.git",
                revision,
            ),
        )


if __name__ == "__main__":
    unittest.main()
