{
  "name": "Mawidi WhatsApp AI Agent",
  "nodes": [
    {
      "parameters": {
        "httpMethod": "POST",
        "path": "mawidi-whatsapp",
        "responseMode": "responseNode",
        "options": {}
      },
      "id": "webhook-whatsapp",
      "name": "WhatsApp Webhook",
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 2,
      "position": [200, 300],
      "webhookId": "mawidi-whatsapp-webhook"
    },
    {
      "parameters": {
        "method": "POST",
        "url": "={{$env.MAWIDI_API_URL}}/api/n8n/context",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Content-Type",
              "value": "application/json"
            }
          ]
        },
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={\n  \"auth_token\": \"{{$env.MAWIDI_WEBHOOK_TOKEN}}\",\n  \"lookup_type\": \"whatsapp_number\",\n  \"lookup_value\": \"{{$json.body.to}}\",\n  \"include\": {\n    \"knowledge_base\": true,\n    \"credentials\": true,\n    \"workflow_config\": true,\n    \"recent_conversations\": true\n  }\n}",
        "options": {}
      },
      "id": "get-context",
      "name": "Get User Context",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [450, 300]
    },
    {
      "parameters": {
        "conditions": {
          "boolean": [
            {
              "value1": "={{$json.success}}",
              "value2": true
            }
          ]
        }
      },
      "id": "check-user",
      "name": "User Found?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2,
      "position": [700, 300]
    },
    {
      "parameters": {
        "resource": "chat",
        "operation": "message",
        "modelId": {
          "__rl": true,
          "value": "gpt-4o-mini",
          "mode": "list"
        },
        "messages": {
          "values": [
            {
              "content": "=You are an AI assistant for {{$node['Get User Context'].json.user.company_name || 'a business'}}. \n\nLanguage: Respond in {{$node['Get User Context'].json.user.language === 'ar' ? 'Arabic' : 'English'}}.\n\nCustom Instructions:\n{{$node['Get User Context'].json.knowledge_base.custom_instructions || 'Be helpful and professional.'}}\n\nFAQ Knowledge:\n{{$node['Get User Context'].json.knowledge_base.faq_summary.map(f => `Q: ${f.question}\\nA: ${f.answer}`).join('\\n\\n') || 'No FAQ available.'}}\n\nRecent conversation context:\n{{$node['Get User Context'].json.recent_conversations?.map(c => c.last_message).join('\\n') || 'No recent messages.'}}"
            },
            {
              "content": "={{$node['WhatsApp Webhook'].json.body.message}}",
              "role": "user"
            }
          ]
        },
        "options": {
          "maxTokens": 500,
          "temperature": 0.7
        }
      },
      "id": "openai-chat",
      "name": "Generate AI Response",
      "type": "@n8n/n8n-nodes-langchain.openAi",
      "typeVersion": 1.4,
      "position": [950, 200],
      "credentials": {
        "openAiApi": {
          "id": "openai-creds",
          "name": "OpenAI Account"
        }
      }
    },
    {
      "parameters": {
        "method": "POST",
        "url": "={{$env.MAWIDI_API_URL}}/api/webhooks/n8n/conversation",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Content-Type",
              "value": "application/json"
            }
          ]
        },
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={\n  \"auth_token\": \"{{$env.MAWIDI_WEBHOOK_TOKEN}}\",\n  \"user_id\": \"{{$node['Get User Context'].json.user.id}}\",\n  \"platform\": \"whatsapp\",\n  \"customer_phone\": \"{{$node['WhatsApp Webhook'].json.body.from}}\",\n  \"customer_name\": \"{{$node['WhatsApp Webhook'].json.body.customer_name || 'Unknown'}}\",\n  \"message\": {\n    \"role\": \"user\",\n    \"content\": \"{{$node['WhatsApp Webhook'].json.body.message}}\",\n    \"timestamp\": \"{{$now.toISO()}}\"\n  }\n}",
        "options": {}
      },
      "id": "log-user-message",
      "name": "Log User Message",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [950, 350]
    },
    {
      "parameters": {
        "method": "POST",
        "url": "={{$env.MAWIDI_API_URL}}/api/webhooks/n8n/conversation",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Content-Type",
              "value": "application/json"
            }
          ]
        },
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={\n  \"auth_token\": \"{{$env.MAWIDI_WEBHOOK_TOKEN}}\",\n  \"user_id\": \"{{$node['Get User Context'].json.user.id}}\",\n  \"conversation_id\": \"{{$node['Log User Message'].json.conversation_id}}\",\n  \"platform\": \"whatsapp\",\n  \"customer_phone\": \"{{$node['WhatsApp Webhook'].json.body.from}}\",\n  \"message\": {\n    \"role\": \"agent\",\n    \"content\": \"{{$node['Generate AI Response'].json.message.content}}\",\n    \"timestamp\": \"{{$now.toISO()}}\"\n  }\n}",
        "options": {}
      },
      "id": "log-agent-response",
      "name": "Log Agent Response",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [1200, 200]
    },
    {
      "parameters": {
        "respondWith": "json",
        "responseBody": "={{ { success: true, response: $node['Generate AI Response'].json.message.content, conversation_id: $node['Log User Message'].json.conversation_id } }}",
        "options": {}
      },
      "id": "respond-success",
      "name": "Respond Success",
      "type": "n8n-nodes-base.respondToWebhook",
      "typeVersion": 1.1,
      "position": [1450, 200]
    },
    {
      "parameters": {
        "respondWith": "json",
        "responseBody": "={{ { success: false, error: 'User not found or inactive' } }}",
        "options": {
          "responseCode": 404
        }
      },
      "id": "respond-not-found",
      "name": "Respond Not Found",
      "type": "n8n-nodes-base.respondToWebhook",
      "typeVersion": 1.1,
      "position": [950, 450]
    }
  ],
  "connections": {
    "WhatsApp Webhook": {
      "main": [
        [
          {
            "node": "Get User Context",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Get User Context": {
      "main": [
        [
          {
            "node": "User Found?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "User Found?": {
      "main": [
        [
          {
            "node": "Generate AI Response",
            "type": "main",
            "index": 0
          },
          {
            "node": "Log User Message",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Respond Not Found",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Generate AI Response": {
      "main": [
        [
          {
            "node": "Log Agent Response",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Log Agent Response": {
      "main": [
        [
          {
            "node": "Respond Success",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "settings": {
    "executionOrder": "v1"
  },
  "staticData": null,
  "meta": {
    "templateCredsSetupCompleted": false,
    "instanceId": "mawidi-instance"
  },
  "pinData": {},
  "versionId": "1",
  "triggerCount": 0,
  "tags": [
    {
      "name": "mawidi",
      "id": "mawidi-tag"
    },
    {
      "name": "whatsapp",
      "id": "whatsapp-tag"
    },
    {
      "name": "ai-agent",
      "id": "ai-agent-tag"
    }
  ]
}
