from app.workflow_guard import _completed_send_invoice_task_evidence


def test_completed_send_invoice_task_allows_workflow_guard_invoice_sent_evidence():
    assert _completed_send_invoice_task_evidence(
        [
            {
                "action_code": "SEND_INVOICE",
                "status": "completed",
                "completed_at": "2026-07-01T15:18:00Z",
                "action": "Enviar fatura",
                "note": "Enviar fatura FA.FA2026.134 ao cliente.",
                "metadata": {"document_number": "FA.FA2026.134"},
            }
        ],
        [
            {
                "id": "doc-fa-134",
                "document_number": "FA.FA2026.134",
            }
        ],
    ) is True


def test_completed_send_invoice_for_other_invoice_does_not_unlock_close():
    assert _completed_send_invoice_task_evidence(
        [
            {
                "action_code": "SEND_INVOICE",
                "status": "completed",
                "completed_at": "2026-07-01T15:18:00Z",
                "action": "Enviar fatura",
                "note": "Enviar fatura FA.FA2026.134 ao cliente.",
                "metadata": {"document_number": "FA.FA2026.134"},
            }
        ],
        [
            {
                "id": "doc-fa-135",
                "document_number": "FA.FA2026.135",
            }
        ],
    ) is False


def test_workflow_guard_context_reads_send_invoice_tasks():
    text = __import__("pathlib").Path("app/workflow_guard.py").read_text()
    assert "SELECT id::text, action_code, action, note, status, metadata" in text
    assert "action_code = 'SEND_INVOICE'" in text
    assert "invoice_sent_from_tasks" in text
    assert '"invoice_sent_evidence": bool(invoice_sent_from_doc or invoice_sent_from_tasks)' in text
