from __future__ import annotations

import unittest

from govoplan_core.core.external_references import (
    ExternalObjectReference,
    ExternalReferenceValidationError,
)


class ExternalReferenceContractTests(unittest.TestCase):
    def test_reference_has_stable_identity_and_ordered_maturity(self) -> None:
        reference = ExternalObjectReference(
            system="openproject-main",
            object_type="work_package",
            object_id="42",
            maturity="synchronize",
            authority_mode="governed_sync",
            canonical_url="https://projects.example.test/work_packages/42",
        )

        self.assertEqual("openproject-main:work_package:42", reference.identity_key)
        self.assertTrue(reference.supports("read"))
        self.assertFalse(reference.supports("replace"))
        self.assertEqual("governed_sync", reference.to_dict()["authority_mode"])

    def test_reference_rejects_credentials_in_urls(self) -> None:
        with self.assertRaises(ExternalReferenceValidationError):
            ExternalObjectReference(
                system="wiki",
                object_type="page",
                object_id="Main_Page",
                canonical_url="https://user:secret@example.test/wiki/Main_Page",
            )

    def test_authority_mode_must_match_maturity(self) -> None:
        with self.assertRaisesRegex(
            ExternalReferenceValidationError,
            "Governed-sync references require synchronize maturity",
        ):
            ExternalObjectReference(
                system="openproject",
                object_type="work_package",
                object_id="7",
                maturity="read",
                authority_mode="governed_sync",
            )


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