import pytest
from tests.base_test import BaseIntegrationTest

# A minimal valid policy payload (does not need to succeed — just to reach auth check)
_POLICY_PAYLOAD = {
    "name": "common_test_policy",
    "attester_type": ["tpm_boot"],
    "content": "cGFja2FnZSB2ZXJpZmljYXRpb24KcmVzdWx0IDo9IHRydWU=",
    "content_type": "text",
}
_CERT_PAYLOAD = {
    "name": "common_test_cert",
    "type": ["tpm_boot"],
    "content": "placeholder",
}
_RV_PAYLOAD = {
    "name": "common_test_rv",
    "attester_type": "tpm_ima",
    "content": "cGxhY2Vob2xkZXI=",
}


class TestCommonConstraints(BaseIntegrationTest):
    """TC-COMMON-* cross-endpoint common constraint tests."""
    __test__ = True

    @pytest.mark.p2
    def test_missing_user_id_rejected_by_management_endpoints(self):
        """TC-COMMON-01: management endpoints reject requests without User-Id → 400"""
        cases = [
            ("POST /policy",    "POST",   "/global-trust-authority/service/v1/policy",    _POLICY_PAYLOAD),
            ("POST /cert",      "POST",   "/global-trust-authority/service/v1/cert",      _CERT_PAYLOAD),
            ("POST /ref_value", "POST",   "/global-trust-authority/service/v1/ref_value", _RV_PAYLOAD),
            ("GET /cert",       "GET",    "/global-trust-authority/service/v1/cert",      None),
        ]

        for label, method, path, payload in cases:
            if method == "POST":
                resp = self.server.post(path, json=payload, headers={"User-Id": None})
            else:
                resp = self.server.get(path, headers={"User-Id": None})

            assert resp.status_code == 400, (
                f"[{label}] expected 400 without User-Id, got {resp.status_code}: {resp.text}"
            )
            msg = self._error_text(resp).lower()
            assert "user" in msg or "missing" in msg or "invalid" in msg or "required" in msg, (
                f"[{label}] expected error mentioning User-Id, got: {msg!r}"
            )