#!/bin/bash
# ═══════════════════════════════════════════════════════════════════
# ZGZ Turismo — Migration: homepage_slides link fields + homepage_content
# Adds link_type / link_poi / link_route / link_url to homepage_slides.
# Also ensures homepage_content exists and ui_translations has
# the 'translations' JSON field and 'ca' column.
#
# Safe to run on an existing Directus instance — skips fields that
# already exist (Directus returns 400 for duplicates, which we ignore).
#
# Usage:  bash scripts/add_homepage_slide_links.sh
# Requires: curl, running zgz_directus container on localhost:8055
# ═══════════════════════════════════════════════════════════════════

set -e

DIRECTUS_URL="${DIRECTUS_URL:-http://localhost:8055}"
ADMIN_EMAIL="${ADMIN_EMAIL:-admin@deusens.com}"
ADMIN_PASSWORD="${ADMIN_PASSWORD:-Admin1234!}"

echo "──────────────────────────────────────────────────────"
echo " ZGZ Turismo — Applying homepage schema migration"
echo " Target: $DIRECTUS_URL"
echo "──────────────────────────────────────────────────────"

# ── 1. Authenticate ──────────────────────────────────────
echo "→ Authenticating..."
TOKEN=$(curl -sf -X POST "$DIRECTUS_URL/auth/login" \
  -H "Content-Type: application/json" \
  -d "{\"email\":\"$ADMIN_EMAIL\",\"password\":\"$ADMIN_PASSWORD\"}" \
  | grep -o '"access_token":"[^"]*"' | head -1 | cut -d'"' -f4)

if [ -z "$TOKEN" ]; then
  echo "✗ Authentication failed. Check ADMIN_EMAIL / ADMIN_PASSWORD."
  exit 1
fi
echo "✓ Authenticated"

# ── Helper: add field (ignores 400 = already exists) ─────
add_field() {
  local COLLECTION="$1"
  local PAYLOAD="$2"
  local FIELD_NAME
  FIELD_NAME=$(echo "$PAYLOAD" | grep -o '"field":"[^"]*"' | head -1 | cut -d'"' -f4)
  HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" \
    -X POST "$DIRECTUS_URL/fields/$COLLECTION" \
    -H "Authorization: Bearer $TOKEN" \
    -H "Content-Type: application/json" \
    -d "$PAYLOAD")
  if [ "$HTTP_CODE" = "200" ] || [ "$HTTP_CODE" = "201" ]; then
    echo "  ✓ $COLLECTION.$FIELD_NAME created"
  elif [ "$HTTP_CODE" = "400" ] || [ "$HTTP_CODE" = "409" ]; then
    echo "  ~ $COLLECTION.$FIELD_NAME already exists (skipped)"
  else
    echo "  ✗ $COLLECTION.$FIELD_NAME failed (HTTP $HTTP_CODE)"
  fi
}

# ── Helper: create collection (ignores 400 = already exists) ─
create_collection() {
  local PAYLOAD="$1"
  local COLL_NAME
  COLL_NAME=$(echo "$PAYLOAD" | grep -o '"collection":"[^"]*"' | head -1 | cut -d'"' -f4)
  HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" \
    -X POST "$DIRECTUS_URL/collections" \
    -H "Authorization: Bearer $TOKEN" \
    -H "Content-Type: application/json" \
    -d "$PAYLOAD")
  if [ "$HTTP_CODE" = "200" ] || [ "$HTTP_CODE" = "201" ]; then
    echo "  ✓ Collection '$COLL_NAME' created"
  elif [ "$HTTP_CODE" = "400" ] || [ "$HTTP_CODE" = "409" ]; then
    echo "  ~ Collection '$COLL_NAME' already exists (skipped)"
  else
    echo "  ✗ Collection '$COLL_NAME' failed (HTTP $HTTP_CODE)"
  fi
}

# ══════════════════════════════════════════════════════════
# 2. Ensure homepage_content singleton exists
# ══════════════════════════════════════════════════════════
echo ""
echo "── homepage_content ──────────────────────────────────"
create_collection '{
  "collection": "homepage_content",
  "meta": { "singleton": true, "icon": "home", "color": "#2196F3",
            "note": "Contenido singleton pagina de inicio" },
  "schema": {},
  "fields": [
    { "field": "id", "type": "integer",
      "schema": { "is_primary_key": true, "has_auto_increment": true },
      "meta": { "hidden": true, "readonly": true } }
  ]
}'

add_field "homepage_content" '{"field":"hero_cta_label","type":"string","meta":{"interface":"input","note":"Texto boton CTA hero"}}'
add_field "homepage_content" '{"field":"intro_text","type":"json","meta":{"interface":"input-code","note":"JSON localizado {\"es-ES\": \"...\"}"}}'
add_field "homepage_content" '{"field":"featured_title","type":"json","meta":{"interface":"input-code"}}'
add_field "homepage_content" '{"field":"featured_heading","type":"json","meta":{"interface":"input-code"}}'
add_field "homepage_content" '{"field":"explore_title","type":"json","meta":{"interface":"input-code"}}'
add_field "homepage_content" '{"field":"coming_soon_title","type":"json","meta":{"interface":"input-code"}}'
add_field "homepage_content" '{"field":"routes_title","type":"json","meta":{"interface":"input-code"}}'
add_field "homepage_content" '{"field":"routes_subtitle","type":"json","meta":{"interface":"input-code"}}'

# ══════════════════════════════════════════════════════════
# 3. Ensure homepage_slides collection exists
# ══════════════════════════════════════════════════════════
echo ""
echo "── homepage_slides ───────────────────────────────────"
create_collection '{
  "collection": "homepage_slides",
  "meta": { "icon": "slideshow", "color": "#2196F3", "sort_field": "sort",
            "note": "Slides del hero slider en la pagina de inicio" },
  "schema": {},
  "fields": [
    { "field": "id", "type": "integer",
      "schema": { "is_primary_key": true, "has_auto_increment": true },
      "meta": { "hidden": true, "readonly": true } }
  ]
}'

add_field "homepage_slides" '{"field":"sort","type":"integer","meta":{"interface":"input-sort","hidden":true}}'
add_field "homepage_slides" '{"field":"status","type":"string","schema":{"default_value":"published"},"meta":{"interface":"select-dropdown","options":{"choices":[{"text":"Published","value":"published"},{"text":"Draft","value":"draft"}]}}}'
add_field "homepage_slides" '{"field":"image","type":"uuid","meta":{"interface":"file-image","note":"Imagen apaisada 1600x900 recomendado"}}'
add_field "homepage_slides" '{"field":"title","type":"json","meta":{"interface":"input-code","note":"JSON localizado {\"es-ES\": \"...\"}"}}'
add_field "homepage_slides" '{"field":"subtitle","type":"json","meta":{"interface":"input-code"}}'

# ── THE 4 NEW LINK FIELDS ─────────────────────────────────
echo ""
echo "── homepage_slides link fields ───────────────────────"
add_field "homepage_slides" '{
  "field": "link_type",
  "type": "string",
  "schema": { "is_nullable": true, "default_value": "none" },
  "meta": {
    "interface": "select-dropdown",
    "note": "Destino al pulsar el slide",
    "options": { "choices": [
      { "text": "Sin enlace", "value": "none" },
      { "text": "POI",        "value": "poi"  },
      { "text": "Ruta",       "value": "route"},
      { "text": "URL Externa","value": "url"  }
    ]}
  }
}'

add_field "homepage_slides" '{
  "field": "link_poi",
  "type": "string",
  "schema": { "is_nullable": true },
  "meta": {
    "interface": "input",
    "note": "Slug del POI (ej: basilica-del-pilar). Solo cuando link_type=poi"
  }
}'

add_field "homepage_slides" '{
  "field": "link_route",
  "type": "string",
  "schema": { "is_nullable": true },
  "meta": {
    "interface": "input",
    "note": "Slug de la ruta. Solo cuando link_type=route"
  }
}'

add_field "homepage_slides" '{
  "field": "link_url",
  "type": "string",
  "schema": { "is_nullable": true },
  "meta": {
    "interface": "input",
    "note": "URL externa completa (https://...). Solo cuando link_type=url"
  }
}'

# ══════════════════════════════════════════════════════════
# 4. Ensure ui_translations has 'translations' JSON + 'ca' fields
# ══════════════════════════════════════════════════════════
echo ""
echo "── ui_translations missing fields ────────────────────"
add_field "ui_translations" '{
  "field": "translations",
  "type": "json",
  "meta": {
    "interface": "input-code",
    "note": "JSON localizado: {\"es-ES\": \"...\", \"en-US\": \"...\"}"
  }
}'
add_field "ui_translations" '{"field":"ca","type":"text","meta":{"interface":"input-multiline","note":"Catala"}}'

# ══════════════════════════════════════════════════════════
# 5. Ensure hotspots has poi_id field
# ══════════════════════════════════════════════════════════
echo ""
echo "── hotspots.poi_id ───────────────────────────────────"
add_field "hotspots" '{"field":"poi_id","type":"integer","meta":{"interface":"many-to-one","hidden":true,"note":"POI al que pertenece este hotspot"}}'

echo ""
echo "══════════════════════════════════════════════════════"
echo " Migration complete."
echo " Run 'bash scripts/apply_schema.sh' to also sync the"
echo " full schema snapshot for future fresh installs."
echo "══════════════════════════════════════════════════════"
