"""G11 — Consolidated audit-log view tests."""
from __future__ import annotations

from datetime import date
from decimal import Decimal

import pytest
from django.contrib.auth import get_user_model
from django.test import RequestFactory
from django.urls import reverse

from apps.mel.indicators.models import (
    Indicator,
    IndicatorFrequency,
    IndicatorTarget,
    LogFrame,
    LogFrameLevel,
    LogFrameRow,
)
from apps.mel.indicators.views import ConsolidatedAuditLogView

pytestmark = pytest.mark.django_db(transaction=True)


User = get_user_model()


def _admin():
    user = User.objects.create_user(email="admin-audit@example.com", password="x")
    user.is_superuser = True
    user.is_staff = True
    user.role = "system_admin"
    user.save()
    return user


def _seed_history():
    admin = _admin()
    lf = LogFrame.objects.create(name="Audit LF", slug="audit-lf", owner=admin)
    row = LogFrameRow.objects.create(
        logframe=lf, level=LogFrameLevel.OUTPUT, title="Row",
    )
    ind = Indicator.objects.create(
        logframe_row=row, code="audit-ind", name="Audit indicator",
        data_source="manual", unit="count", calculation_method="count",
        frequency=IndicatorFrequency.MONTHLY,
    )
    IndicatorTarget.objects.create(
        indicator=ind, period_label="2026-04",
        period_start=date(2026, 4, 1), period_end=date(2026, 4, 30),
        baseline_value=Decimal("0"), target_value=Decimal("50"),
    )
    return admin, ind


def test_consolidated_audit_log_renders_mixed_models():
    admin, ind = _seed_history()
    rf = RequestFactory()
    req = rf.get(reverse("mel_indicators:audit_log"))
    req.user = admin
    response = ConsolidatedAuditLogView.as_view()(req)
    assert response.status_code == 200
    html = response.content.decode()
    assert "Indicator" in html
    assert "Strategic Objective" in html
    assert "IndicatorTarget" in html


def test_audit_log_filters_by_model():
    admin, ind = _seed_history()
    rf = RequestFactory()
    req = rf.get(reverse("mel_indicators:audit_log") + "?model=Indicator")
    req.user = admin
    response = ConsolidatedAuditLogView.as_view()(req)
    html = response.content.decode()
    # Only Indicator badges; LogFrame and IndicatorTarget should not appear as
    # row badges (their names may still appear elsewhere in the chrome, so we
    # specifically check for the badge cell).
    assert ">Indicator<" in html
    # The empty-state copy should NOT fire because we have at least one row.
    assert "No matching audit entries" not in html


def test_audit_log_filters_by_invalid_user_returns_empty():
    admin, _ = _seed_history()
    rf = RequestFactory()
    req = rf.get(reverse("mel_indicators:audit_log") + "?user=no-such-user-xyz")
    req.user = admin
    response = ConsolidatedAuditLogView.as_view()(req)
    html = response.content.decode()
    assert "No matching audit entries" in html


def test_mel_officer_can_view_audit_log():
    """FRSME-MEI016 / MEI022: the MEL Officer is an authorised MEL user and
    must be able to read the consolidated (read-only) audit trail."""
    _seed_history()
    officer = User.objects.create_user(email="officer-audit@example.com", password="x")
    officer.role = "mel_officer"
    officer.save()
    rf = RequestFactory()
    req = rf.get(reverse("mel_indicators:audit_log"))
    req.user = officer
    response = ConsolidatedAuditLogView.as_view()(req)
    assert response.status_code == 200
