#!/usr/bin/env bash
set -u
set -o pipefail

BASE_URL="${BASE_URL:-http://127.0.0.1:8020}"
PGHOST="${PGHOST:-192.168.1.110}"
PGUSER="${PGUSER:-clientflow}"
PGDATABASE="${PGDATABASE:-clientflow}"

if [ -z "${PGPASSWORD:-}" ]; then
  echo "Define PGPASSWORD antes de correr."
  exit 2
fi

code() {
  local method="$1"
  local url="$2"
  shift 2
  curl -s -o /dev/null -w "%{http_code}\n" -X "$method" "$url" "$@"
}

echo "== Odoo ClientFlow integration test =="

echo -n "GET /integrations -> "
code GET "$BASE_URL/integrations"

echo -n "POST /integrations/odoo/test -> "
code POST "$BASE_URL/integrations/odoo/test" -H "Content-Type: application/x-www-form-urlencoded"

echo -n "POST /integrations/odoo/sync-products -> "
code POST "$BASE_URL/integrations/odoo/sync-products" -H "Content-Type: application/x-www-form-urlencoded"

echo
echo "Produtos com metadata Odoo:"
PGPASSWORD="$PGPASSWORD" psql -h "$PGHOST" -U "$PGUSER" -d "$PGDATABASE" -c "
SELECT
  count(*) FILTER (WHERE metadata ? 'odoo') AS synced_products,
  count(*) FILTER (WHERE COALESCE((metadata->'odoo'->>'has_bom')::boolean, false)) AS with_bom,
  count(*) FILTER (WHERE COALESCE((metadata->'odoo'->'stock'->>'available')::numeric, 0) > 0) AS with_available_stock,
  max(metadata->'odoo'->>'last_synced_at') AS last_synced_at
FROM products;
"

echo
echo "Amostra:"
PGPASSWORD="$PGPASSWORD" psql -h "$PGHOST" -U "$PGUSER" -d "$PGDATABASE" -c "
SELECT
  sku,
  name,
  metadata->'odoo'->>'product_id' AS odoo_id,
  metadata->'odoo'->'stock'->>'available' AS available,
  metadata->'odoo'->>'has_bom' AS has_bom
FROM products
WHERE metadata ? 'odoo'
ORDER BY name
LIMIT 15;
"

echo
echo "Sync runs:"
PGPASSWORD="$PGPASSWORD" psql -h "$PGHOST" -U "$PGUSER" -d "$PGDATABASE" -c "
SELECT sync_type, status, total_seen, total_changed, total_errors, message, started_at, finished_at
FROM odoo_sync_runs
ORDER BY started_at DESC
LIMIT 10;
"
