import datetime

from meal_manager.models import Event, Household, Subscription
from meal_manager.scripts import apply_subscriptions


def test_subscriptions(db_session):
    now = datetime.datetime.now()
    event1 = Event(
        title="far future",
        event_time=now + datetime.timedelta(days=8, hours=2),
        registration_deadline=now + datetime.timedelta(days=3),
        description="This event should not be proceesed.",
    )
    event2 = Event(
        title="soon",
        event_time=now + datetime.timedelta(days=7, hours=2),
        registration_deadline=now + datetime.timedelta(days=2),
        description="This event should be proceesed.",
    )
    ignore = Event(
        title="ignore me",
        event_time=now + datetime.timedelta(days=7, hours=2),
        description=(
            "This event should not be proceesed because it "
            "has ignore_subscriptions set to True."
        ),
        registration_deadline=now + datetime.timedelta(days=2, hours=2),
        ignore_subscriptions=True,
    )
    db_session.add(event1)
    db_session.add(event2)
    db_session.add(ignore)

    db_session.add(Household(name="Klaus", id=1))
    db_session.add(
        Subscription(
            household_id=1,
            num_adult_meals=2,
            num_children_meals=1,
            num_small_children_meals=0,
            comment="test",
        )
    )
    db_session.commit()

    assert not event1.subscriptions_applied
    assert not event2.subscriptions_applied

    apply_subscriptions(db_session)

    assert len(event1.registrations) == 0
    assert len(event2.registrations) == 1
    assert len(ignore.registrations) == 0
    assert not event1.subscriptions_applied
    assert not ignore.subscriptions_applied
    assert event2.subscriptions_applied
    assert event2.registrations[0].comment is not None
    assert "test" in event2.registrations[0].comment
