"""Tests for audit logging."""

import json
import os
import tempfile

from pyauthz import AuditLogger, JsonExporter, PyAuthz, Resource, Role, Subject


class TestAuditLogging:
    def test_json_exporter_writes_events(self):
        fd, path = tempfile.mkstemp(suffix=".jsonl")
        os.close(fd)
        try:
            rp = PyAuthz()
            rp.add_role(Role(name="admin", permissions=["*:*"]))
            audit = AuditLogger(exporters=[JsonExporter(path=path)])
            rp.set_audit_logger(audit)

            user = Subject(id="alice", roles=["admin"])
            doc = Resource(id="doc-1", type="documents")
            rp.is_allowed(user, "read", doc)

            with open(path) as f:
                lines = f.readlines()
            assert len(lines) == 1

            event = json.loads(lines[0])
            assert event["subject_id"] == "alice"
            assert event["action"] == "documents:read"
            assert event["decision"] == "ALLOW"
            assert event["resource_type"] == "documents"
            assert event["resource_id"] == "doc-1"
            assert "duration_us" in event
        finally:
            os.unlink(path)

    def test_audit_logs_denied(self):
        fd, path = tempfile.mkstemp(suffix=".jsonl")
        os.close(fd)
        try:
            rp = PyAuthz()
            rp.add_role(Role(name="viewer", permissions=["documents:read"]))
            audit = AuditLogger(exporters=[JsonExporter(path=path)])
            rp.set_audit_logger(audit)

            user = Subject(id="bob", roles=["viewer"])
            doc = Resource(id="doc-1", type="documents")
            rp.is_allowed(user, "write", doc)

            with open(path) as f:
                event = json.loads(f.readline())
            assert event["decision"] == "DENY"
            assert event["subject_id"] == "bob"
        finally:
            os.unlink(path)

    def test_multiple_events_logged(self):
        fd, path = tempfile.mkstemp(suffix=".jsonl")
        os.close(fd)
        try:
            rp = PyAuthz()
            rp.add_role(Role(name="admin", permissions=["*:*"]))
            audit = AuditLogger(exporters=[JsonExporter(path=path)])
            rp.set_audit_logger(audit)

            user = Subject(id="alice", roles=["admin"])
            doc = Resource(id="doc-1", type="documents")
            rp.is_allowed(user, "read", doc)
            rp.is_allowed(user, "write", doc)
            rp.is_allowed(user, "delete", doc)

            with open(path) as f:
                lines = f.readlines()
            assert len(lines) == 3
        finally:
            os.unlink(path)
