
"""V5.7 tests for real monitoring CRUD operations."""

from pathlib import Path

from sentinel.monitoring.store import MonitoringStore


def test_user_group_rule_and_schedule_crud(tmp_path: Path) -> None:
    store = MonitoringStore(tmp_path / "monitoring.db")
    store.initialize()

    user_id = store.create_user(
        email="user@example.org",
        display_name="Test User",
        role_code="OPERATOR",
    )
    group_id = store.create_group(
        group_code="CS4",
        display_name="Frankenstein",
        site_code="LCSB",
        description="Test group",
    )

    store.assign_equipment_to_group(
        equipment_id="freezer-test-001",
        group_id=group_id,
    )
    store.assign_user_to_group(
        user_id=user_id,
        group_id=group_id,
        can_view=True,
        can_acknowledge=True,
        can_manage_alarms=False,
    )

    rule_id = store.create_alarm_rule(
        name="High temperature",
        scope_type="GROUP",
        scope_id="CS4",
        category="THRESHOLD",
        severity="WARNING",
        metric="internal_temperature_c",
        operator="above",
        threshold=-15.0,
    )

    schedule_id = store.create_alarm_schedule(
        name="Maintenance",
        scope_type="GROUP",
        scope_id="CS4",
        starts_at="2026-08-10T10:00",
        ends_at="2026-08-10T12:00",
        reason="Maintenance",
        created_by="Test User",
    )

    assert store.get_users()[0]["group_codes"] == "CS4"
    assert store.get_group_equipment_ids(group_id) == ["freezer-test-001"]
    assert store.get_alarm_rules()[0]["id"] == rule_id
    assert store.get_alarm_schedules()[0]["id"] == schedule_id


def test_alarm_lifecycle(tmp_path: Path) -> None:
    store = MonitoringStore(tmp_path / "monitoring.db")
    store.initialize()

    alarm_id = store.open_or_update_alarm(
        equipment_id="freezer-test-001",
        category="THRESHOLD",
        severity="WARNING",
        code="RULE-1",
        title="High temperature",
        message="-10 > -15",
        suppressed=False,
        suppression_schedule_id=None,
    )

    store.acknowledge_alarm(
        alarm_id,
        actor="Operator",
        comment="Checking equipment",
    )
    assert store.get_alarms()[0]["state"] == "ACKNOWLEDGED"

    store.resolve_alarm(
        alarm_id,
        actor="Operator",
        comment="Temperature restored",
    )
    assert store.get_alarms()[0]["state"] == "RESOLVED"
