"""Phase 2.4 — RIMS grant linkage search endpoint (FRREP-MCL009).

The wizard's grant picker searches *active or completed* funding records
(APPROVED / CLOSED) by public_grant_id + title. Drafts and pending-approval
records are never offered.
"""
from __future__ import annotations

from datetime import date, timedelta
from decimal import Decimal

import pytest
from django.test import Client
from django.urls import reverse

from apps.rims.grants.models import FundingRecord


def _grant(public_grant_id, title, status):
    return FundingRecord.objects.create(
        public_grant_id=public_grant_id,
        title=title,
        amount=Decimal("1000"),
        start_date=date.today(),
        end_date=date.today() + timedelta(days=365),
        status=status,
    )


@pytest.mark.django_db
def test_grant_search_requires_login(client):
    resp = client.get(reverse("repo_integration:grant_search"), {"q": "RU"})
    assert resp.status_code in (302, 403)


@pytest.mark.django_db
def test_grant_search_returns_only_linkable_statuses(submitter_user):
    _grant("RU/2021/APPROVED", "Maize resilience", FundingRecord.Status.APPROVED)
    _grant("RU/2020/CLOSED", "Closed soil project", FundingRecord.Status.CLOSED)
    _grant("RU/2022/DRAFT", "Draft idea", FundingRecord.Status.DRAFT)
    _grant("RU/2022/PENDING", "Pending review", FundingRecord.Status.PENDING_APPROVAL)

    client = Client()
    client.force_login(submitter_user)
    resp = client.get(reverse("repo_integration:grant_search"), {"q": "RU"})
    assert resp.status_code == 200
    ids = {r["id"] for r in resp.json()["results"]}
    assert ids == {"RU/2021/APPROVED", "RU/2020/CLOSED"}


@pytest.mark.django_db
def test_grant_search_matches_title(submitter_user):
    _grant("RU/2021/APPROVED", "Maize resilience", FundingRecord.Status.APPROVED)
    _grant("RU/2020/CLOSED", "Soil carbon", FundingRecord.Status.CLOSED)

    client = Client()
    client.force_login(submitter_user)
    resp = client.get(reverse("repo_integration:grant_search"), {"q": "carbon"})
    ids = {r["id"] for r in resp.json()["results"]}
    assert ids == {"RU/2020/CLOSED"}
