"""Non-functional invariants from PRD §5.3.4 (Phase 1)."""
from __future__ import annotations

import pytest
from django.core.exceptions import ValidationError
from apps.mel.indicators.models import (
    LogFrame,
    LogFrameLevel,
    LogFrameRow,
)

pytestmark = pytest.mark.django_db


def test_multiple_impact_rows_per_logframe_allowed():
    """M&E SRS Table 62 — a Strategic Objective may have one or many Impacts.

    Supersedes the old ``uniq_impact_per_logframe`` cap (one impact per frame),
    which contradicted the SRS.
    """
    lf = LogFrame.objects.create(name="LF-impact", slug="lf-impact")
    LogFrameRow.objects.create(logframe=lf, level=LogFrameLevel.IMPACT, title="First")
    LogFrameRow.objects.create(logframe=lf, level=LogFrameLevel.IMPACT, title="Second")
    assert lf.rows.filter(level=LogFrameLevel.IMPACT).count() == 2


def test_two_logframes_may_each_have_their_own_impact():
    lf1 = LogFrame.objects.create(name="LF-A", slug="lf-a")
    lf2 = LogFrame.objects.create(name="LF-B", slug="lf-b")
    LogFrameRow.objects.create(logframe=lf1, level=LogFrameLevel.IMPACT, title="A impact")
    # Different logframe — allowed.
    LogFrameRow.objects.create(logframe=lf2, level=LogFrameLevel.IMPACT, title="B impact")


def test_deleting_logframe_row_with_children_raises_validation_error():
    lf = LogFrame.objects.create(name="LF-del", slug="lf-del")
    impact = LogFrameRow.objects.create(logframe=lf, level=LogFrameLevel.IMPACT, title="I")
    LogFrameRow.objects.create(logframe=lf, level=LogFrameLevel.OUTCOME, title="O", parent=impact)

    with pytest.raises(ValidationError):
        impact.delete()


def test_deleting_leaf_row_is_permitted():
    lf = LogFrame.objects.create(name="LF-leaf", slug="lf-leaf")
    impact = LogFrameRow.objects.create(logframe=lf, level=LogFrameLevel.IMPACT, title="I")
    outcome = LogFrameRow.objects.create(logframe=lf, level=LogFrameLevel.OUTCOME, title="O", parent=impact)

    outcome.delete()
    assert not LogFrameRow.objects.filter(pk=outcome.pk).exists()
