from pathlib import Path

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


def test_payment_confirmed_filters_obsolete_payment_followups_from_next_action_ui():
    page = (ROOT / "app/admin_ui/pages/opportunities.py").read_text(encoding="utf-8")
    assert "_OBSOLETE_AFTER_PAYMENT_TASK_CODES" in page
    assert "_is_obsolete_after_payment_task" in page
    assert "pending_tasks = [t for t in all_pending_tasks if not _is_obsolete_after_payment_task(t, payment_confirmed_for_ui)]" in page
    assert "obsoleta: pagamento já confirmado" in page


def test_payment_confirmed_cleanup_closes_obsolete_tasks_when_registered():
    operation_service = (ROOT / "app/operation_service.py").read_text(encoding="utf-8")
    task_service = (ROOT / "app/task_service.py").read_text(encoding="utf-8")
    assert "mark_obsolete_payment_followup_tasks" in operation_service
    assert 'action_key or "") == "payment_confirmed"' in operation_service
    assert "FOLLOW_UP_PROFORMA" in task_service
    assert "FOLLOW_UP_PAYMENT" in task_service


def test_opportunity_messages_include_message_raw_event_fallback():
    service = (ROOT / "app/communication_service.py").read_text(encoding="utf-8")
    assert "_list_message_backed_chatwoot_items_for_opportunity" in service
    assert "raw_event_conversation_id" in service
    assert "JOIN messages m ON m.source_system = 'chatwoot'" in service
    assert "list_communications_for_opportunity" in service


def test_fiscal_data_blocks_invoice_and_jasmin_action_is_explicit():
    rules = (ROOT / "app/domain/opportunity_flow/rules.py").read_text(encoding="utf-8")
    page = (ROOT / "app/admin_ui/pages/opportunities.py").read_text(encoding="utf-8")
    assert "Pagamento confirmado com dados fiscais incompletos" in rules
    assert "Completar dados fiscais" in rules
    assert "Completar com dados Jasmin" in page
    assert "Jasmin encontrado, mas não contém novos campos" in page
