#!/usr/bin/env bash
# Spec 035/043 — Cria plano + produto FOSS ligbox-mail-business (VM123)
set -euo pipefail

FOSS_URL="${FOSS_URL:-https://financeiro.ligbox.com.br}"
ADMIN_EMAIL="${FOSS_ADMIN_EMAIL:-admin@ligbox.com.br}"
ADMIN_PASS="${FOSS_ADMIN_PASS:-LbFossAdmin805353}"
PLAN_NAME="${PLAN_NAME:-ligbox-mail-business}"
PRODUCT_SLUG="${PRODUCT_SLUG:-ligbox-mail-business}"
PRODUCT_TITLE="${PRODUCT_TITLE:-Ligbox Mail Business}"
PRICE="${PRICE:-549.00}"
COOKIE_JAR="$(mktemp)"
trap 'rm -f "$COOKIE_JAR"' EXIT

echo "=== FOSS: criar ${PRODUCT_SLUG} ==="

curl -sk -c "$COOKIE_JAR" -b "$COOKIE_JAR" -X POST "${FOSS_URL}/api/guest/staff/login" \
  -d "email=${ADMIN_EMAIL}&password=${ADMIN_PASS}" | grep -q '"role":"admin"' || { echo "Login falhou"; exit 1; }
curl -sk -c "$COOKIE_JAR" -b "$COOKIE_JAR" "${FOSS_URL}/admin" >/dev/null
CSRF=$(awk '$6=="csrf_token" {print $7}' "$COOKIE_JAR" | tail -1)

# Hosting plan OpenPanel
PLANS=$(curl -sk -b "$COOKIE_JAR" "${FOSS_URL}/api/admin/servicehosting/hp_get_list?CSRFToken=${CSRF}")
if ! echo "$PLANS" | grep -q "${PLAN_NAME}"; then
  curl -sk -b "$COOKIE_JAR" -X POST "${FOSS_URL}/api/admin/servicehosting/hp_create" \
    -d "CSRFToken=${CSRF}&name=${PLAN_NAME}" >/dev/null
  echo "Plano hosting ${PLAN_NAME} criado"
else
  echo "Plano hosting ${PLAN_NAME} já existe"
fi

HP_ID=$(echo "$PLANS" | python3 -c "
import sys,json,re
d=json.load(sys.stdin)
items=d.get('result',{}).get('list',[]) if isinstance(d.get('result'),dict) else d.get('list',[])
name='${PLAN_NAME}'
for i in items:
    if i.get('name')==name:
        print(i.get('id')); break
" 2>/dev/null || true)
if [[ -z "$HP_ID" ]]; then
  PLANS2=$(curl -sk -b "$COOKIE_JAR" "${FOSS_URL}/api/admin/servicehosting/hp_get_list?CSRFToken=${CSRF}")
  HP_ID=$(echo "$PLANS2" | python3 -c "
import sys,json
d=json.load(sys.stdin)
items=d.get('result',{}).get('list',[]) if isinstance(d.get('result'),dict) else d.get('list',[])
for i in items:
    if i.get('name')=='${PLAN_NAME}':
        print(i.get('id')); break
")
fi
echo "hp_id=${HP_ID}"

SERVER_ID=$(curl -sk -b "$COOKIE_JAR" "${FOSS_URL}/api/admin/servicehosting/server_get_list?CSRFToken=${CSRF}" | python3 -c "
import sys,json
d=json.load(sys.stdin)
items=d.get('result',{}).get('list',[]) if isinstance(d.get('result'),dict) else d.get('list',[])
print(items[0]['id'] if items else '1')
")
echo "server_id=${SERVER_ID}"

LIST=$(curl -sk -b "$COOKIE_JAR" -X POST "${FOSS_URL}/api/admin/product/get_list" \
  -d "CSRFToken=${CSRF}&per_page=100")
if echo "$LIST" | grep -q "${PRODUCT_SLUG}"; then
  PID=$(echo "$LIST" | python3 -c "
import sys,json
d=json.load(sys.stdin)
items=d.get('result',{}).get('list',[]) if isinstance(d.get('result'),dict) else d.get('list',[])
for i in items:
    if i.get('slug')=='${PRODUCT_SLUG}':
        print(i.get('id')); break
")
  echo "Produto ${PRODUCT_SLUG} já existe id=${PID}"
  exit 0
fi

PID=$(curl -sk -b "$COOKIE_JAR" -X POST "${FOSS_URL}/api/admin/product/prepare" \
  -d "CSRFToken=${CSRF}&title=${PRODUCT_TITLE// /+}&type=hosting" | python3 -c "import sys,json; print(json.load(sys.stdin)['result'])")

curl -sk -b "$COOKIE_JAR" -X POST "${FOSS_URL}/api/admin/product/update_config" \
  --data-urlencode "CSRFToken=${CSRF}" --data-urlencode "id=${PID}" \
  --data-urlencode "config[server_id]=${SERVER_ID}" \
  --data-urlencode "config[hosting_plan_id]=${HP_ID}" \
  --data-urlencode "config[reseller]=0" \
  --data-urlencode "config[allow_domain_own]=1" \
  --data-urlencode "config[allow_domain_register]=0" \
  --data-urlencode "config[allow_domain_transfer]=0" \
  --data-urlencode "config[allow_subdomain]=0" >/dev/null

curl -sk -b "$COOKIE_JAR" -X POST "${FOSS_URL}/api/admin/product/update" \
  -d "CSRFToken=${CSRF}&id=${PID}&status=enabled&slug=${PRODUCT_SLUG}" >/dev/null

echo "Produto criado: id=${PID} slug=${PRODUCT_SLUG} plan=${PLAN_NAME} price=R\$${PRICE}"
echo "Actualizar foss-products.md com product_id=${PID}"
