"""Tests for audit trail checksum calculation."""

import hashlib

from apiposture_pro.enterprise.audit_trail.checksum import compute_scan_checksum


def test_checksum_is_deterministic():
    cs1 = compute_scan_checksum(1, "2026-04-01T12:00:00+00:00", "/tmp/test", '[{"rule_id":"AP001"}]')
    cs2 = compute_scan_checksum(1, "2026-04-01T12:00:00+00:00", "/tmp/test", '[{"rule_id":"AP001"}]')
    assert cs1 == cs2


def test_checksum_is_64_hex_chars():
    cs = compute_scan_checksum(1, "2026-04-01T12:00:00+00:00", "/tmp/test", "[]")
    assert len(cs) == 64
    assert all(c in "0123456789abcdef" for c in cs)


def test_checksum_changes_when_findings_change():
    cs1 = compute_scan_checksum(1, "2026-04-01T12:00:00+00:00", "/tmp/test", '[{"rule_id":"AP001"}]')
    cs2 = compute_scan_checksum(1, "2026-04-01T12:00:00+00:00", "/tmp/test", '[{"rule_id":"AP999"}]')
    assert cs1 != cs2


def test_checksum_changes_when_path_changes():
    cs1 = compute_scan_checksum(1, "2026-04-01T12:00:00+00:00", "/tmp/test", "[]")
    cs2 = compute_scan_checksum(1, "2026-04-01T12:00:00+00:00", "/tmp/other", "[]")
    assert cs1 != cs2


def test_checksum_changes_when_timestamp_changes():
    cs1 = compute_scan_checksum(1, "2026-04-01T12:00:00+00:00", "/tmp/test", "[]")
    cs2 = compute_scan_checksum(1, "2026-04-01T13:00:00+00:00", "/tmp/test", "[]")
    assert cs1 != cs2


def test_checksum_changes_when_id_changes():
    cs1 = compute_scan_checksum(1, "2026-04-01T12:00:00+00:00", "/tmp/test", "[]")
    cs2 = compute_scan_checksum(2, "2026-04-01T12:00:00+00:00", "/tmp/test", "[]")
    assert cs1 != cs2


def test_checksum_matches_manual_sha256():
    scan_id = 42
    timestamp = "2026-04-01T12:00:00+00:00"
    path = "/tmp/api"
    findings = '[{"rule_id":"AP001"}]'
    expected_raw = f"{scan_id}{timestamp}{path}{findings}"
    expected = hashlib.sha256(expected_raw.encode("utf-8")).hexdigest()
    assert compute_scan_checksum(scan_id, timestamp, path, findings) == expected


def test_checksum_with_empty_findings():
    cs = compute_scan_checksum(1, "2026-04-01T00:00:00+00:00", "/app", "[]")
    assert len(cs) == 64


def test_checksum_string_id_same_as_int():
    cs_int = compute_scan_checksum(1, "2026-04-01T12:00:00+00:00", "/tmp", "[]")
    cs_str = compute_scan_checksum("1", "2026-04-01T12:00:00+00:00", "/tmp", "[]")
    # Both convert to the same string representation "1"
    assert cs_int == cs_str
