"""Closes the SRS gap where Fellowships have no dedicated progress-monitoring
model (unlike scholarships' AcademicProgressReport) — they previously fell
back to the generic milestone/tranche mechanism with no fellowship-specific
reporting fields.
"""
from datetime import date, timedelta
from decimal import Decimal

import pytest
from django.db import IntegrityError
from django.utils import timezone

from apps.rims.grants.models import Application, FellowshipProgressReport, GrantCall
from apps.rims.grants.services import award_application, shortlist_application, submit_application


def _fellowship_award(applicant_user, institution, *, suffix="fpr"):
    call = GrantCall.objects.create(
        title="Fellowship progress call",
        slug=f"fpr-{suffix}-{int(timezone.now().timestamp())}",
        call_type=GrantCall.CallType.FELLOWSHIP,
        opens_at=timezone.now() - timedelta(days=1),
        closes_at=timezone.now() + timedelta(days=10),
        status=GrantCall.Status.PUBLISHED,
    )
    app = Application.objects.create(call=call, applicant=applicant_user, institution=institution)
    submit_application(app)
    app = Application.objects.get(pk=app.pk)
    shortlist_application(app)
    award_application(app, Decimal("1000"), date.today() + timedelta(days=180), narrative="")
    return Application.objects.get(pk=app.pk).award


@pytest.mark.django_db
def test_create_fellowship_progress_report(applicant_user, institution):
    award = _fellowship_award(applicant_user, institution)
    report = FellowshipProgressReport.objects.create(
        award=award,
        period_label="Month 3",
        host_institution_feedback="Fellow is settling in well.",
        activities_completed="Delivered two guest lectures.",
    )
    assert award.fellowship_progress_reports.count() == 1
    assert report.status == FellowshipProgressReport.Status.SUBMITTED


@pytest.mark.django_db
def test_unique_period_per_award(applicant_user, institution):
    award = _fellowship_award(applicant_user, institution, suffix="uniq")
    FellowshipProgressReport.objects.create(award=award, period_label="Month 3")
    with pytest.raises(IntegrityError):
        FellowshipProgressReport.objects.create(award=award, period_label="Month 3")
