"""System event log: persist, dedup, summary, acknowledge."""

from __future__ import annotations

import pytest

from app.services import system_event_service as svc
from tests.conftest import _test_session_factory  # type: ignore


@pytest.fixture
async def session():
    async with _test_session_factory() as s:
        yield s


async def test_log_and_list(session):
    row = await svc.log_event(
        session,
        severity="warning",
        source="ingestion",
        code="ohlcv_stale",
        message="No new bars since 2026-06-23",
        symbol="SATS",
        dedup_key="ohlcv_stale:SATS",
    )
    assert row is not None
    assert row.severity == "warning"

    events = await svc.list_events(session, days=7)
    assert len(events) == 1
    assert events[0].symbol == "SATS"


async def test_dedup_suppresses_repeat(session):
    first = await svc.log_event(
        session,
        severity="error",
        source="data_collector",
        code="job_error",
        message="boom",
        dedup_key="job:data_collector:error",
    )
    second = await svc.log_event(
        session,
        severity="error",
        source="data_collector",
        code="job_error",
        message="boom again",
        dedup_key="job:data_collector:error",
    )
    assert first is not None
    assert second is None
    events = await svc.list_events(session, days=7)
    assert len(events) == 1


async def test_summary_and_acknowledge(session):
    await svc.log_event(
        session,
        severity="error",
        source="job",
        code="job_error",
        message="fail",
        dedup_key="a",
    )
    await svc.log_event(
        session,
        severity="warning",
        source="job",
        code="job_rate_limited",
        message="slow",
        dedup_key="b",
    )
    s = await svc.summary(session, days=7)
    assert s["total"] == 2
    assert s["unacknowledged"] == 2
    assert s["unacknowledged_errors"] == 1
    assert s["unacknowledged_warnings"] == 1

    n = await svc.acknowledge_all(session, days=7)
    assert n == 2
    s2 = await svc.summary(session, days=7)
    assert s2["unacknowledged"] == 0
    assert s2["total"] == 2
