from __future__ import annotations

from decimal import Decimal

import pytest

from quartermaster import service
from quartermaster.models import Section


def test_add_and_total(db):
    service.add_entry(db, Section.income, "Paycheck", Decimal("2500.00"))
    service.add_entry(db, Section.income, "Side gig", Decimal("250.50"))
    entries = service.list_entries(db, Section.income)
    assert [e.name for e in entries] == ["Paycheck", "Side gig"]
    assert service.section_total(entries) == Decimal("2750.50")


def test_delete_entry(db):
    entry = service.add_entry(db, Section.other, "One-off", Decimal("10.00"))
    service.delete_entry(db, entry.id)
    assert service.list_entries(db, Section.other) == []


def test_set_debt_target(db):
    dm = service.add_entry(db, Section.debt_minimum, "Card A", Decimal("50.00"))
    target = service.set_debt_target(db, dm.id)
    assert target.debt_minimum_id == dm.id
    assert target.entry is not None and target.entry.name == "Card A"


def test_debt_target_rejects_non_debt_minimum(db):
    income = service.add_entry(db, Section.income, "Paycheck", Decimal("1.00"))
    with pytest.raises(ValueError):
        service.set_debt_target(db, income.id)


def test_debt_target_cleared_on_delete(db):
    dm = service.add_entry(db, Section.debt_minimum, "Card B", Decimal("75.00"))
    service.set_debt_target(db, dm.id)
    service.delete_entry(db, dm.id)
    target = service.get_debt_target(db)
    assert target.debt_minimum_id is None
