"""PRD §5.1 FRFA-CS003 — pre-populate call form with inherited fields from parent funding record.

Also covers the FRFA-CS004 empty-state when no APPROVED funding has uncommitted balance.
"""
from datetime import date, timedelta
from decimal import Decimal

import pytest

from apps.rims.grants.models import FundingRecord
from apps.rims.operations.models import Partner


@pytest.fixture
def gm_user_mfa(grants_manager_user):
    """Pre-seed a verified TOTP so MFAEnforcementMiddleware doesn't bounce to /accounts/mfa/setup/."""
    from apps.core.authentication.models import MFADevice

    MFADevice.objects.create(
        user=grants_manager_user,
        device_type=MFADevice.DeviceType.TOTP,
        name="Test TOTP",
        secret="JBSWY3DPEHPK3PXP",
        is_verified=True,
    )
    return grants_manager_user


def _approved_funding(amount="50000", partner=None):
    return FundingRecord.objects.create(
        title="Climate Resilience 2026",
        amount=Decimal(amount),
        start_date=date.today(),
        end_date=date.today() + timedelta(days=365),
        status=FundingRecord.Status.APPROVED,
        partner=partner,
    )


@pytest.mark.django_db
def test_call_create_inherits_from_funding_when_query_param_set(client, gm_user_mfa):
    partner = Partner.objects.create(name="Donor X", country="Uganda")
    fr = _approved_funding(partner=partner)

    client.force_login(gm_user_mfa)
    resp = client.get(f"/rims/grants/manage/calls/new/?funding={fr.pk}")

    assert resp.status_code == 200
    ctx = resp.context
    assert ctx["inherited_funding"].pk == fr.pk
    assert ctx["inherited_funding_balance"] == Decimal("50000.00")
    # Form initial pre-fills the FK fields.
    assert ctx["form"].initial.get("funding_record") == fr.pk
    assert ctx["form"].initial.get("partner") == partner.pk
    # Banner rendered.
    assert b"Inherited from funding record" in resp.content
    assert b"Climate Resilience 2026" in resp.content


@pytest.mark.django_db
def test_call_create_without_query_param_shows_no_banner(client, gm_user_mfa):
    _approved_funding()
    client.force_login(gm_user_mfa)
    resp = client.get("/rims/grants/manage/calls/new/")

    assert resp.status_code == 200
    assert resp.context.get("inherited_funding") is None
    assert b"Inherited from funding record" not in resp.content


@pytest.mark.django_db
def test_call_create_unknown_funding_id_falls_back_to_blank(client, gm_user_mfa):
    client.force_login(gm_user_mfa)
    resp = client.get("/rims/grants/manage/calls/new/?funding=99999")

    assert resp.status_code == 200
    assert resp.context.get("inherited_funding") is None
    # CS004 empty-state surfaces because no APPROVED funding with balance exists.
    assert b"No funding capacity" in resp.content


@pytest.mark.django_db
def test_call_create_rejects_unapproved_funding(client, gm_user_mfa):
    draft = FundingRecord.objects.create(
        title="Draft FR",
        amount=Decimal("1000"),
        start_date=date.today(),
        end_date=date.today() + timedelta(days=30),
        status=FundingRecord.Status.DRAFT,
    )
    client.force_login(gm_user_mfa)
    resp = client.get(f"/rims/grants/manage/calls/new/?funding={draft.pk}")

    assert resp.status_code == 200
    assert resp.context.get("inherited_funding") is None


@pytest.mark.django_db
def test_funding_detail_shows_create_call_cta_when_approved(client, gm_user_mfa):
    fr = _approved_funding()
    client.force_login(gm_user_mfa)
    resp = client.get(f"/rims/grants/manage/funding/{fr.pk}/")

    assert resp.status_code == 200
    assert b"New call from this funding" in resp.content
    assert f"?funding={fr.pk}".encode() in resp.content
