#!/bin/bash
#
# Get CONTRACT_TEST_API_KEY from the database
#
# Usage:
#   ./get-api-key.sh                    # Uses env vars or defaults
#   ./get-api-key.sh --docker           # Query via docker exec
#   ./get-api-key.sh --host db.example.com --password secret
#
# Environment variables:
#   DB_HOST, DB_PORT, DB_NAME, DB_USER, DB_PASSWORD
#

set -e

# Defaults
DB_HOST="${DB_HOST:-localhost}"
DB_PORT="${DB_PORT:-5432}"
DB_NAME="${DB_NAME:-amarback}"
DB_USER="${DB_USER:-postgres}"
DB_PASSWORD="${DB_PASSWORD:-}"
DOCKER_CONTAINER=""

# Parse arguments
while [[ $# -gt 0 ]]; do
    case $1 in
        --docker)
            DOCKER_CONTAINER="${2:-core_nest_db}"
            shift 2 || shift 1
            ;;
        --host)
            DB_HOST="$2"
            shift 2
            ;;
        --port)
            DB_PORT="$2"
            shift 2
            ;;
        --name)
            DB_NAME="$2"
            shift 2
            ;;
        --user)
            DB_USER="$2"
            shift 2
            ;;
        --password)
            DB_PASSWORD="$2"
            shift 2
            ;;
        --help|-h)
            echo "Usage: $0 [options]"
            echo ""
            echo "Options:"
            echo "  --docker [container]  Query via docker exec (default: core_nest_db)"
            echo "  --host HOST           Database host"
            echo "  --port PORT           Database port (default: 5432)"
            echo "  --name NAME           Database name (default: amarback)"
            echo "  --user USER           Database user (default: postgres)"
            echo "  --password PASS       Database password"
            echo ""
            echo "Environment variables: DB_HOST, DB_PORT, DB_NAME, DB_USER, DB_PASSWORD"
            exit 0
            ;;
        *)
            echo "Unknown option: $1" >&2
            exit 1
            ;;
    esac
done

QUERY="SELECT key FROM common_apikey WHERE is_active=true LIMIT 1;"

if [[ -n "$DOCKER_CONTAINER" ]]; then
    # Query via docker
    API_KEY=$(docker exec "$DOCKER_CONTAINER" psql -U "$DB_USER" -d "$DB_NAME" -t -c "$QUERY" 2>/dev/null | tr -d ' \n')
else
    # Query directly
    export PGPASSWORD="$DB_PASSWORD"
    API_KEY=$(psql -h "$DB_HOST" -p "$DB_PORT" -U "$DB_USER" -d "$DB_NAME" -t -c "$QUERY" 2>/dev/null | tr -d ' \n')
fi

if [[ -z "$API_KEY" ]]; then
    echo "Error: No active API key found in database" >&2
    exit 1
fi

echo "$API_KEY"
