"""
T-UC1: Trustee — Spesenverarbeitung.

Verifies that the trustee feature instances are correctly configured
with RMA accounting and that system workflow templates exist.
"""

import pytest
from tests.demo.conftest import _getFeatureInstances


class TestTrusteeSetup:

    def test_trusteeInstancesExist(self, db, mandateHappylife, mandateAlpina):
        """Both mandates must have a trustee instance."""
        for mandate in [mandateHappylife, mandateAlpina]:
            mid = mandate.get("id")
            instances = _getFeatureInstances(db, mid, "trustee")
            assert len(instances) >= 1, f"No trustee in {mandate.get('label')}"

    def test_rmaCredentialsEncrypted(self, db, mandateHappylife):
        """RMA config must have non-empty encrypted credentials."""
        from modules.features.trustee.datamodelFeatureTrustee import TrusteeAccountingConfig
        mid = mandateHappylife.get("id")
        instances = _getFeatureInstances(db, mid, "trustee")
        iid = instances[0].get("id")
        configs = db.getRecordset(TrusteeAccountingConfig, recordFilter={"featureInstanceId": iid})
        assert configs
        enc = configs[0].get("encryptedConfig", "")
        assert enc and len(enc) > 10, "encryptedConfig should be a non-trivial encrypted blob"

    def test_rmaCredentialsDecryptable(self, db, mandateHappylife):
        """Encrypted RMA config must be decryptable and contain expected keys."""
        import json
        from modules.features.trustee.datamodelFeatureTrustee import TrusteeAccountingConfig
        from modules.shared.configuration import decryptValue
        mid = mandateHappylife.get("id")
        instances = _getFeatureInstances(db, mid, "trustee")
        iid = instances[0].get("id")
        configs = db.getRecordset(TrusteeAccountingConfig, recordFilter={"featureInstanceId": iid})
        enc = configs[0].get("encryptedConfig", "")
        plain = json.loads(decryptValue(enc, userId="system", keyName="accountingConfig"))
        assert "apiBaseUrl" in plain
        assert "clientName" in plain
        assert "apiKey" in plain
        assert plain["apiKey"], "apiKey should not be empty"


class TestSystemWorkflowTemplates:

    def test_systemTemplatesExist(self, db):
        """System workflow templates should exist (created by system bootstrap, not demo config)."""
        from modules.features.graphicalEditor.datamodelFeatureGraphicalEditor import AutoWorkflow
        try:
            templates = db.getRecordset(AutoWorkflow, recordFilter={"isTemplate": True, "templateScope": "system"})
        except Exception:
            pytest.skip("AutoWorkflow table not accessible from app DB")
            return
        if len(templates) == 0:
            pytest.skip("No system workflow templates — run full system bootstrap first")
