#!/bin/bash
# Creates Directus Flow: on contact_submissions create -> send email notification
BASE="http://localhost:8055"
TOKEN=$(curl -s -X POST "$BASE/auth/login" -H "Content-Type: application/json" \
  -d '{"email":"admin@deusens.com","password":"Admin1234!"}' | jq -r '.data.access_token')

# Create the Flow
FLOW=$(curl -s -X POST "$BASE/flows" -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" -d '{
    "name": "Contact Form Email Notification",
    "icon": "email",
    "color": "#795548",
    "status": "active",
    "trigger": "event",
    "options": {
      "type": "action",
      "scope": ["items.create"],
      "collections": ["contact_submissions"]
    }
  }')
FLOW_ID=$(echo "$FLOW" | jq -r '.data.id')
echo "Flow created: $FLOW_ID"

# Add email operation
curl -s -X POST "$BASE/operations" -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" -d "{
    \"name\": \"Send notification email\",
    \"key\": \"send_email\",
    \"type\": \"mail\",
    \"position_x\": 19,
    \"position_y\": 1,
    \"flow\": \"$FLOW_ID\",
    \"options\": {
      \"to\": [\"turismo@zaragoza.es\"],
      \"subject\": \"Nuevo mensaje de contacto - {{$trigger.payload.name}}\",
      \"body\": \"<h2>Nuevo mensaje de contacto</h2><p><b>Nombre:</b> {{$trigger.payload.name}}</p><p><b>Email:</b> {{$trigger.payload.email}}</p><p><b>Asunto:</b> {{$trigger.payload.subject}}</p><p><b>Mensaje:</b><br>{{$trigger.payload.message}}</p><p><b>Fuente:</b> {{$trigger.payload.source}} | <b>Idioma:</b> {{$trigger.payload.language}}</p><p><b>POI:</b> {{$trigger.payload.poi_slug}}</p>\"
    }
  }" > /dev/null
echo "Email operation added to flow"
echo "Flow setup complete - contact form will send emails to turismo@zaragoza.es"
