"""POST /forms/{id}/fields — adding fields to a form that is already
published, without versioning it or taking it offline."""


async def _published_form(client, headers) -> dict:
    resp = await client.post(
        "/forms",
        headers=headers,
        json={"name": "Pytest Intake", "field_definitions": [{"name": "subject", "type": "text", "label": "Subject", "required": True}]},
    )
    assert resp.status_code == 201, resp.text
    published = await client.post(f"/forms/{resp.json()['form_id']}/publish", headers=headers)
    assert published.status_code == 200
    return published.json()


async def test_fields_are_added_in_place_and_stay_optional(client, auth_headers):
    form = await _published_form(client, auth_headers)
    sub = await client.post(
        "/form-submissions",
        headers=auth_headers,
        json={"form_id": form["form_id"], "form_version": form["version"], "field_values": {"subject": "Before"}},
    )
    assert sub.status_code == 201, sub.text

    resp = await client.post(
        f"/forms/{form['form_id']}/fields",
        headers=auth_headers,
        json={"field_definitions": [{"name": "region", "type": "text", "label": "Region", "required": True, "required_message": "x"}]},
    )
    assert resp.status_code == 200, resp.text
    body = resp.json()
    assert (body["version"], body["status"]) == (form["version"], "published")
    assert [f["name"] for f in body["field_definitions"]] == ["subject", "region"]
    assert body["field_definitions"][0]["required"] is True  # untouched
    assert body["field_definitions"][1]["required"] is False and body["field_definitions"][1]["required_message"] is None

    # Earlier submissions still edit cleanly, and the new field can be filled.
    edit = await client.patch(
        f"/form-submissions/{sub.json()['id']}", headers=auth_headers, json={"field_values": {"subject": "After", "region": "South"}}
    )
    assert edit.status_code == 200, edit.text


async def test_duplicate_names_are_refused(client, auth_headers):
    form = await _published_form(client, auth_headers)
    again = await client.post(
        f"/forms/{form['form_id']}/fields", headers=auth_headers, json={"field_definitions": [{"name": "subject", "type": "text", "label": "Subject 2"}]}
    )
    assert again.status_code == 409
    twice = await client.post(
        f"/forms/{form['form_id']}/fields",
        headers=auth_headers,
        json={"field_definitions": [{"name": "a", "type": "text", "label": "A"}, {"name": "a", "type": "text", "label": "A2"}]},
    )
    assert twice.status_code == 409
    empty = await client.post(f"/forms/{form['form_id']}/fields", headers=auth_headers, json={"field_definitions": []})
    assert empty.status_code == 422
