"""POST /tools-settings accepts and round-trips ticket_emails via JSON."""
from unittest.mock import patch

from fastapi.testclient import TestClient

from app.main import app

client = TestClient(app)
TENANT = "org_8c32bf3e-6a18-4739-9b1c-94c0cf11125f"


def test_json_body_passes_ticket_emails_through():
    with patch("app.api.endpoints.bootstrap_tenant"), \
         patch("app.api.endpoints.save_tool_settings") as save:
        save.return_value = {"features": {}, "email": {}, "providers": {}, "ticket_emails": []}
        client.post("/tools-settings", json={
            "tenant_id": TENANT,
            "ticket_emails": [{"email": "sales@acme.com", "category": "Sales"}]})

    assert save.call_args.kwargs["ticket_emails"] == [
        {"email": "sales@acme.com", "category": "Sales"}]


def test_an_empty_ticket_emails_list_is_still_sent_through_to_clear_it():
    # Distinct from omitting the key entirely -- an empty list must reach
    # save_tool_settings so a tenant can remove every business email.
    with patch("app.api.endpoints.bootstrap_tenant"), \
         patch("app.api.endpoints.save_tool_settings") as save:
        save.return_value = {"features": {}, "email": {}, "providers": {}, "ticket_emails": []}
        client.post("/tools-settings", json={"tenant_id": TENANT, "ticket_emails": []})

    assert save.call_args.kwargs["ticket_emails"] == []


def test_ticket_emails_alone_is_enough_to_pass_validation():
    with patch("app.api.endpoints.bootstrap_tenant"), \
         patch("app.api.endpoints.save_tool_settings") as save:
        save.return_value = {"features": {}, "email": {}, "providers": {}, "ticket_emails": []}
        resp = client.post("/tools-settings", json={
            "tenant_id": TENANT,
            "ticket_emails": [{"email": "sales@acme.com", "category": "Sales"}]})

    assert resp.status_code == 200


def test_an_invalid_ticket_email_reaches_the_client_as_a_400():
    with patch("app.api.endpoints.bootstrap_tenant"), \
         patch("app.api.endpoints.save_tool_settings",
              side_effect=ValueError("'bad' is not a valid email address.")):
        resp = client.post("/tools-settings", json={
            "tenant_id": TENANT,
            "ticket_emails": [{"email": "bad", "category": "Sales"}]})

    assert resp.status_code == 400
