from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]


def read(path: str) -> str:
    return (ROOT / path).read_text(encoding="utf-8")


def test_opportunity_stage_dropdown_is_simplified_to_commercial_phases():
    opps = read("app/admin_ui/pages/opportunities.py")
    assert "COMMERCIAL_STAGE_OPTIONS" in opps
    assert "Alterar fase comercial" in opps
    assert "Lista curta: detalhes como fatura, pagamento, Odoo, produção e envio" in opps
    assert "_commercial_stage_options_html(stage)" in opps
    assert "Estado atual detalhado:" in opps
    assert "Orçamento enviado" in opps
    assert "A aguardar pagamento" in opps
    assert "Pagamento confirmado" in opps
    assert "Encomenda confirmada / em execução" in opps
    assert "Pró-forma / pagamento" not in opps


def test_opportunity_has_payment_terms_card_for_non_linear_flows():
    opps = read("app/admin_ui/pages/opportunities.py")
    assert "Condições comerciais" in opps
    assert "sem forçar um fluxo único" in opps
    assert "PAYMENT_TERM_LABELS" in opps
    assert "before_shipping" in opps
    assert "after_delivery" in opps
    assert "Pagamento pós-entrega" in opps
    assert "preparação/envio podem avançar" in opps
    assert "orçamento → pagamento → fatura" in opps
    assert "commercial_terms_card_html" in opps
    assert "{commercial_terms_card_html}" in opps


def test_opportunity_commercial_terms_are_persisted_in_metadata():
    opps = read("app/admin_ui/pages/opportunities.py")
    assert '@router.post("/opportunities/{opportunity_id}/commercial-terms")' in opps
    assert "payment_terms" in opps
    assert "delivery_terms" in opps
    assert "commercial_terms_note" in opps
    assert "metadata = COALESCE(metadata, '{}'::jsonb) || CAST(:payload AS JSONB)" in opps
