#!/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}"
OPP_ID="${OPP_ID:-}"

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

psqlc() {
  PGPASSWORD="$PGPASSWORD" PAGER=cat psql \
    -h "$PGHOST" \
    -U "$PGUSER" \
    -d "$PGDATABASE" \
    -v ON_ERROR_STOP=1 \
    -c "$1"
}

psqlq() {
  PGPASSWORD="$PGPASSWORD" PAGER=cat psql \
    -h "$PGHOST" \
    -U "$PGUSER" \
    -d "$PGDATABASE" \
    -At \
    -v ON_ERROR_STOP=1 \
    -c "$1"
}

if [ -z "$OPP_ID" ]; then
  OPP_ID="$(psqlq "
    SELECT opportunity_id
    FROM operation_links
    WHERE system='odoo'
      AND external_type='sale_order'
    ORDER BY updated_at DESC
    LIMIT 1;
  ")"
fi

echo "== Teste estado físico Odoo =="
echo "OPP_ID=$OPP_ID"
echo

echo "Venda Odoo ligada:"
psqlc "
SELECT
  opportunity_id,
  external_id,
  external_name,
  external_url,
  status,
  updated_at
FROM operation_links
WHERE opportunity_id::text = '$OPP_ID'
  AND system='odoo'
  AND external_type='sale_order';
"

echo
echo -n "POST sync-status -> "
curl -s -o /dev/null -w "%{http_code}\n" \
  -X POST "$BASE_URL/opportunities/$OPP_ID/odoo/sync-status"

echo
echo "Estado físico guardado:"
psqlc "
SELECT
  opportunity_id,
  external_id,
  external_name,
  status,
  payload->>'label' AS label,
  payload->>'reason' AS reason,
  payload->>'next_action' AS next_action,
  payload->>'ready_to_ship' AS ready_to_ship,
  updated_at
FROM operation_links
WHERE opportunity_id::text = '$OPP_ID'
  AND system='odoo'
  AND external_type='physical_status'
ORDER BY updated_at DESC
LIMIT 1;
"

echo
echo "Resumo Odoo:"
psqlc "
SELECT
  payload->'sale_order' AS sale_order,
  jsonb_array_length(COALESCE(payload->'pickings', '[]'::jsonb)) AS pickings,
  jsonb_array_length(COALESCE(payload->'productions', '[]'::jsonb)) AS productions
FROM operation_links
WHERE opportunity_id::text = '$OPP_ID'
  AND system='odoo'
  AND external_type='physical_status'
ORDER BY updated_at DESC
LIMIT 1;
"
