from __future__ import annotations

from decimal import Decimal

from quartermaster import month_service, service
from quartermaster.models import Section


def test_template_edit_does_not_mutate_existing_month_and_applies_to_next(db):
    # seed the template
    twitch = service.add_entry(
        db, Section.subscription, "Twitch", Decimal("10.99")
    )

    # create April 2026 (snapshots the current template)
    april = month_service.create_month(db, "2026-04")
    april_twitch = next(
        e for e in april.entries if e.source_entry_id == twitch.id
    )
    assert april_twitch.planned == Decimal("10.99")
    assert april_twitch.origin_planned == Decimal("10.99")
    assert april_twitch.name == "Twitch"
    assert april_twitch.origin_name == "Twitch"

    # edit the template
    service.update_entry(
        db, twitch.id, name="Twitch Prime", amount=Decimal("11.99")
    )

    # april is untouched
    db.refresh(april_twitch)
    assert april_twitch.planned == Decimal("10.99")
    assert april_twitch.origin_planned == Decimal("10.99")
    assert april_twitch.name == "Twitch"
    assert april_twitch.origin_name == "Twitch"

    # creating May 2026 picks up the new values
    may = month_service.create_month(db, "2026-05")
    may_twitch = next(e for e in may.entries if e.source_entry_id == twitch.id)
    assert may_twitch.planned == Decimal("11.99")
    assert may_twitch.origin_planned == Decimal("11.99")
    assert may_twitch.name == "Twitch Prime"
    assert may_twitch.origin_name == "Twitch Prime"
