#!/usr/bin/env bash
set -euo pipefail

# Registers only the dedicated OCI API signing key for the QA vector store,
# then applies sql/adb/75_*.sql.  The narrow outbound HTTPS ACL is an ADMIN
# operation and must be applied before this script runs.
# Secrets stay in environment variables and are never written to this repo.

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
: "${SGMP_POC_DB_PASSWORD:?SGMP_POC_DB_PASSWORD is required}"

SQLCL_BIN="${SQLCL_BIN:-sql}"
SGMP_POC_DB_USER="${SGMP_POC_DB_USER:-SGMP_POC}"
SGMP_POC_DB_SERVICE="${SGMP_POC_DB_SERVICE:-sgmpaipoc_low}"
SGMP_POC_WALLET_DIR="${SGMP_POC_WALLET_DIR:?SGMP_POC_WALLET_DIR is required}"
VECTOR_OCI_USER_OCID="${VECTOR_OCI_USER_OCID:?VECTOR_OCI_USER_OCID is required}"
VECTOR_OCI_TENANCY_OCID="${VECTOR_OCI_TENANCY_OCID:?VECTOR_OCI_TENANCY_OCID is required}"
VECTOR_OCI_COMPARTMENT_OCID="${VECTOR_OCI_COMPARTMENT_OCID:?VECTOR_OCI_COMPARTMENT_OCID is required}"
VECTOR_OCI_API_KEY_FILE="${VECTOR_OCI_API_KEY_FILE:?VECTOR_OCI_API_KEY_FILE is required}"
VECTOR_OCI_API_KEY_FINGERPRINT="${VECTOR_OCI_API_KEY_FINGERPRINT:?VECTOR_OCI_API_KEY_FINGERPRINT is required}"

command -v "$SQLCL_BIN" >/dev/null
command -v jq >/dev/null
[[ -f "$SGMP_POC_WALLET_DIR/tnsnames.ora" ]]
[[ -f "$VECTOR_OCI_API_KEY_FILE" ]]

private_key_json="$(jq -Rs . "$VECTOR_OCI_API_KEY_FILE")"
credential_params="$(jq -cn \
  --arg user_ocid "$VECTOR_OCI_USER_OCID" \
  --arg tenancy_ocid "$VECTOR_OCI_TENANCY_OCID" \
  --arg compartment_ocid "$VECTOR_OCI_COMPARTMENT_OCID" \
  --argjson private_key "$private_key_json" \
  --arg fingerprint "$VECTOR_OCI_API_KEY_FINGERPRINT" \
  '{user_ocid:$user_ocid, tenancy_ocid:$tenancy_ocid, compartment_ocid:$compartment_ocid, private_key:$private_key, fingerprint:$fingerprint}')"
credential_params_b64="$(printf '%s' "$credential_params" | base64 | tr -d '\n')"

"$SQLCL_BIN" -thin -L -S -tnsadmin "$SGMP_POC_WALLET_DIR" /nolog <<SQL
whenever oserror exit failure
connect ${SGMP_POC_DB_USER}/"${SGMP_POC_DB_PASSWORD}"@${SGMP_POC_DB_SERVICE}
whenever sqlerror exit sql.sqlcode
DECLARE
  v_params CLOB := utl_i18n.raw_to_char(
    utl_encode.base64_decode(utl_raw.cast_to_raw('${credential_params_b64}')),
    'AL32UTF8'
  );
BEGIN
  BEGIN
    DBMS_VECTOR.DROP_CREDENTIAL('SGMP_POC_QA_VECTOR_CRED');
  EXCEPTION WHEN OTHERS THEN
    IF SQLCODE != -20004 THEN RAISE; END IF;
  END;
  DBMS_VECTOR.CREATE_CREDENTIAL(
    credential_name => 'SGMP_POC_QA_VECTOR_CRED',
    params          => JSON(v_params)
  );
END;
/
@${ROOT}/sql/adb/75_sgmp_qa_vector_retrieval.sql
SELECT config_key, config_value FROM sg_qa_vector_config ORDER BY config_key;
exit success
SQL
