{
  "name": "Simulaci\u00f3n de Sensores (cada 5 min)",
  "nodes": [
    {
      "parameters": {
        "rule": {
          "interval": [
            {
              "field": "minutes",
              "minutesInterval": 5
            }
          ]
        }
      },
      "id": "schedule",
      "name": "Schedule Trigger (5 min)",
      "type": "n8n-nodes-base.scheduleTrigger",
      "typeVersion": 1,
      "position": [
        200,
        300
      ]
    },
    {
      "parameters": {
        "jsCode": "// === Configuraci\u00f3n de sensores simulados ===\n// Editar este arreglo con los datos reales obtenidos desde el panel\n// Admin \u2192 Sensores \u2192 \"Ver token\". sensorId debe coincidir con el ID\n// devuelto en la creaci\u00f3n del sensor.\n//\n// Tambi\u00e9n se pueden definir v\u00eda variables de entorno:\n//   SENSORES_JSON='[{\"sensorId\":1,\"token\":\"<jwt>\",\"tipo\":\"clima\"}, ...]'\n\nlet sensores = [];\nif ($env.SENSORES_JSON) {\n  try { sensores = JSON.parse($env.SENSORES_JSON); }\n  catch (e) { throw new Error('SENSORES_JSON inv\u00e1lido: ' + e.message); }\n} else {\n  sensores = [\n    // { sensorId: 1, token: 'eyJhbGciOiJI...', tipo: 'clima' },\n    // { sensorId: 2, token: 'eyJhbGciOiJI...', tipo: 'suelo' },\n    // { sensorId: 3, token: 'eyJhbGciOiJI...', tipo: 'riego' },\n  ];\n}\n\nif (!Array.isArray(sensores) || sensores.length === 0) {\n  return [{ json: { _skip: true, reason: 'No hay sensores configurados. Edite el nodo \"Generar lecturas\" o defina SENSORES_JSON.' } }];\n}\n\nconst r = (min, max) => Math.round((min + Math.random() * (max - min)) * 100) / 100;\n\nconst tipos = {\n  clima: () => ({\n    tempMax: r(20, 34),\n    tempMin: r(8, 18),\n    precipitacion: Math.random() > 0.7 ? r(0.5, 25) : 0,\n    humedadRelativa: r(40, 90),\n    radiacionSolar: r(15, 28),\n    velocidadViento: r(3, 22),\n  }),\n  suelo: () => ({\n    humedad: r(18, 55),\n    ph: r(5.5, 7.8),\n    nitrogenoDisponible: r(18, 50),\n    fosforoDisponible: r(10, 35),\n    conductividadElectrica: r(0.8, 2.5),\n  }),\n  riego: () => ({\n    tipoRiego: ['Goteo', 'Aspersi\u00f3n', 'Pivote Central'][Math.floor(Math.random() * 3)],\n    volumenAplicadoL: Math.round(r(800, 4500)),\n    duracionHoras: r(0.5, 4),\n    presionBar: r(1.0, 3.5),\n  }),\n};\n\nconst out = [];\nfor (const s of sensores) {\n  const gen = tipos[s.tipo];\n  if (!gen) continue;\n  out.push({ json: { sensorId: s.sensorId, token: s.token, data: { fecha: new Date().toISOString().split('T')[0], ...gen() } } });\n}\n\nreturn out;"
      },
      "id": "generar-lecturas",
      "name": "Generar lecturas",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        420,
        300
      ]
    },
    {
      "parameters": {
        "conditions": {
          "string": [
            {
              "value1": "={{ $json._skip }}",
              "operation": "isEmpty"
            }
          ]
        }
      },
      "id": "filter-valid",
      "name": "Filter Valid",
      "type": "n8n-nodes-base.if",
      "typeVersion": 1,
      "position": [
        640,
        300
      ]
    },
    {
      "parameters": {
        "method": "POST",
        "url": "={{ $env.AGROTECH_API_URL || 'http://host.docker.internal:3001' }}/webhooks/sensores/datos",
        "sendBody": true,
        "contentType": "json",
        "body": "={{ $json }}",
        "options": {
          "response": {
            "response": {
              "fullResponse": false,
              "neverError": true
            }
          }
        }
      },
      "id": "post-datos",
      "name": "POST /webhooks/sensores/datos",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.1,
      "position": [
        860,
        240
      ]
    }
  ],
  "connections": {
    "Schedule Trigger (5 min)": {
      "main": [
        [
          {
            "node": "Generar lecturas",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Generar lecturas": {
      "main": [
        [
          {
            "node": "Filter Valid",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Filter Valid": {
      "main": [
        [
          {
            "node": "POST /webhooks/sensores/datos",
            "type": "main",
            "index": 0
          }
        ],
        []
      ]
    }
  }
}