from __future__ import annotations


def test_index_renders_all_sections(client):
    response = client.get("/")
    assert response.status_code == 200
    for label in [
        "Incomes",
        "Fixed Amount Bills",
        "Debt Minimums",
        "Food and Essentials",
        "Subscriptions",
        "Other",
        "Primary Debt Target",
    ]:
        assert label in response.text


def test_add_entry_updates_total(client):
    response = client.post(
        "/sections/income/entries",
        data={"name": "Paycheck", "amount": "2500.00"},
    )
    assert response.status_code == 200
    assert "Paycheck" in response.text
    assert "$2500.00" in response.text


def test_add_debt_minimum_also_returns_target_card(client):
    response = client.post(
        "/sections/debt_minimum/entries",
        data={"name": "Card A", "amount": "40.00"},
    )
    assert response.status_code == 200
    assert "section-debt_minimum" in response.text
    assert "section-debt_target" in response.text


def test_delete_entry(client):
    create = client.post(
        "/sections/other/entries", data={"name": "Gift", "amount": "25.00"}
    )
    assert create.status_code == 200
    response = client.delete("/entries/1")
    assert response.status_code == 200
    assert "Gift" not in response.text
    assert "$0.00" in response.text


def test_set_and_clear_debt_target(client):
    client.post(
        "/sections/debt_minimum/entries",
        data={"name": "Card A", "amount": "40.00"},
    )
    set_resp = client.post("/debt-target", data={"debt_minimum_id": "1"})
    assert set_resp.status_code == 200
    assert "Card A" in set_resp.text

    clear_resp = client.post("/debt-target", data={"debt_minimum_id": ""})
    assert clear_resp.status_code == 200
    assert "No target selected" in clear_resp.text


def test_debt_target_clears_when_referenced_row_deleted(client):
    client.post(
        "/sections/debt_minimum/entries",
        data={"name": "Card A", "amount": "40.00"},
    )
    client.post("/debt-target", data={"debt_minimum_id": "1"})
    del_resp = client.delete("/entries/1")
    assert del_resp.status_code == 200
    assert "No target selected" in del_resp.text


def test_reject_negative_amount(client):
    response = client.post(
        "/sections/other/entries", data={"name": "Bad", "amount": "-5"}
    )
    assert response.status_code == 400


def test_reject_non_debt_minimum_target(client):
    client.post(
        "/sections/income/entries",
        data={"name": "Paycheck", "amount": "10.00"},
    )
    response = client.post("/debt-target", data={"debt_minimum_id": "1"})
    assert response.status_code == 400
