#!/bin/bash
# Uses vault cache for fast token retrieval

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "${SCRIPT_DIR}/../vault-env.sh"

NOCODB_TOKEN=$(vaul…ken)

if [ -z "$NOCODB_TOKEN" ]; then
    echo "Error: Could not retrieve NocoDB token"
    exit 1
fi

echo "Fixing SingleSelect columns in NocoDB..."
echo "Got NocoDB token"
# Get column IDs
echo "Fetching column IDs..."
COLS=$(curl -s "http://192.168.25.5:8080/api/v2/meta/tables/mx149yctebfwvys" -H "xc-token: $NOCODB_TOKEN")
TYPE_ID=$(echo "$COLS" | jq -r '.columns[] | select(.title=="type") | .id')
SEVERITY_ID=$(echo "$COLS" | jq -r '.columns[] | select(.title=="severity") | .id')
STATUS_ID=$(echo "$COLS" | jq -r '.columns[] | select(.title=="status") | .id')
echo "type column ID: $TYPE_ID"
echo "severity column ID: $SEVERITY_ID"
echo "status column ID: $STATUS_ID"
# Fix type column
echo ""
echo "Fixing type column..."
curl -s -X PATCH "http://192.168.25.5:8080/api/v2/meta/columns/$TYPE_ID" \
  -H "xc-token: $NOCODB_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"dtxp": "'"'"'correction'"'"','"'"'preference'"'"','"'"'episode'"'"','"'"'decision'"'"','"'"'validation'"'"'"}' | jq -r '.columns[] | select(.title=="type") | .dtxp'
# Fix severity column
echo ""
echo "Fixing severity column..."
curl -s -X PATCH "http://192.168.25.5:8080/api/v2/meta/columns/$SEVERITY_ID" \
  -H "xc-token: $NOCODB_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"dtxp": "'"'"'error'"'"','"'"'warning'"'"','"'"'auto-correct'"'"'"}' | jq -r '.columns[] | select(.title=="severity") | .dtxp'
# Fix status column
echo ""
echo "Fixing status column..."
curl -s -X PATCH "http://192.168.25.5:8080/api/v2/meta/columns/$STATUS_ID" \
  -H "xc-token: $NOCODB_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"dtxp": "'"'"'active'"'"','"'"'reversed'"'"','"'"'deprecated'"'"'"}' | jq -r '.columns[] | select(.title=="status") | .dtxp'
echo ""
echo "Done!"
