from __future__ import annotations

import unittest

from govoplan_core.security.secrets import (
    TransientPayloadError,
    open_transient_payload,
    seal_transient_payload,
)


class TransientPayloadTests(unittest.TestCase):
    def test_round_trip_preserves_json_object(self) -> None:
        token = seal_transient_payload(
            {
                "purpose": "test",
                "tenant_id": "tenant-1",
                "selected": ["one", "two"],
            }
        )

        self.assertEqual(
            {
                "purpose": "test",
                "tenant_id": "tenant-1",
                "selected": ["one", "two"],
            },
            open_transient_payload(token, ttl_seconds=60),
        )

    def test_tampered_payload_is_rejected(self) -> None:
        token = seal_transient_payload({"purpose": "test"})
        replacement = "A" if token[-1] != "A" else "B"

        with self.assertRaisesRegex(
            TransientPayloadError, "invalid or expired"
        ):
            open_transient_payload(f"{token[:-1]}{replacement}", ttl_seconds=60)

    def test_non_positive_ttl_is_rejected(self) -> None:
        token = seal_transient_payload({"purpose": "test"})

        with self.assertRaisesRegex(ValueError, "TTL must be positive"):
            open_transient_payload(token, ttl_seconds=0)


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