import pytest
import time
import json
from cloud.audit.enterprise_audit import EnterpriseAuditLog

@pytest.fixture
def audit(tmp_path):
    return EnterpriseAuditLog(tmp_path)

def test_log_and_search(audit):
    team = "team_1"
    audit.log(team, "user_1", "create_chain", "chain_1")
    audit.log(team, "user_2", "delete_chain", "chain_1")
    audit.log(team, "user_1", "run_chain", "chain_1")
    audit.log("team_2", "user_3", "run_chain", "chain_2")
    
    results = audit.search(team)
    assert len(results) == 3
    assert results[0]["team_id"] == team
    
    filtered = audit.search(team, action="create_chain")
    assert len(filtered) == 1
    assert filtered[0]["user_id"] == "user_1"

def test_apply_retention(audit):
    audit.log("team_1", "user_1", "action_1", "res_1")
    
    # artificially age the entry
    entries = []
    with open(audit.log_file, "r") as f:
        for line in f:
            e = json.loads(line)
            e["timestamp"] -= (400 * 86400) # > 365 days
            entries.append(e)
            
    with open(audit.log_file, "w") as f:
        for e in entries:
            f.write(json.dumps(e) + "\n")
            
    audit.apply_retention(max_days=365)
    
    results = audit.search("team_1")
    assert len(results) == 0

def test_retention_policy(audit):
    policy = audit.get_retention_policy("team_X")
    assert policy["max_days"] == 365
    
    audit.set_retention_policy("team_X", 90, True, True)
    policy = audit.get_retention_policy("team_X")
    assert policy["max_days"] == 90
    assert policy["auto_delete"] is True
