"""Audit log: privileged actions are recorded and the hash chain is tamper-evident."""

from __future__ import annotations

import uuid

from legate.audit.service import verify_chain
from legate.db.models.audit import AuditLog
from sqlalchemy import select


def test_privileged_actions_are_audited(client, helpers):
    ctx = helpers.bootstrap_owner(client)
    helpers.add_member(client, ctx["access_token"], email="m@example.com", role="viewer")
    resp = client.get("/audit", headers=helpers.headers(ctx["access_token"]))
    assert resp.status_code == 200
    actions = [e["action"] for e in resp.json()]
    assert "workspace.create" in actions
    assert "member.invite" in actions


def test_first_entry_has_no_previous_hash(client, helpers):
    ctx = helpers.bootstrap_owner(client)
    entries = client.get("/audit", headers=helpers.headers(ctx["access_token"])).json()
    # Returned newest-first; the oldest (workspace.create) starts the chain.
    first = entries[-1]
    assert first["hash_prev"] is None
    assert first["hash"]


def test_hash_chain_verifies(client, helpers, db):
    ctx = helpers.bootstrap_owner(client)
    helpers.add_member(client, ctx["access_token"], email="m@example.com", role="builder")
    ws_id = uuid.UUID(ctx["workspace"]["id"])
    assert verify_chain(db, ws_id) is True


def test_tampering_breaks_the_chain(client, helpers, db):
    ctx = helpers.bootstrap_owner(client)
    ws_id = uuid.UUID(ctx["workspace"]["id"])
    assert verify_chain(db, ws_id) is True

    # Mutate a recorded entry: the recomputed hash no longer matches.
    entry = db.scalars(select(AuditLog).where(AuditLog.workspace_id == ws_id)).first()
    entry.action = "tampered.action"
    db.commit()

    assert verify_chain(db, ws_id) is False
