#!/usr/bin/env bash

# Deploy Financial Tokenization Service
# This script deploys the tokenization service to Kubernetes

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/../lib/init.sh"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
# Load .env via dotenv (RPC CR/LF trim). Fallback: raw source.
if [[ -f "$SCRIPT_DIR/../lib/deployment/dotenv.sh" ]]; then
  # shellcheck disable=SC1090
  source "$SCRIPT_DIR/../lib/deployment/dotenv.sh"
  load_deployment_env --repo-root "${PROJECT_ROOT:-$REPO_ROOT}"
elif [[ -n "${PROJECT_ROOT:-}" && -f "$PROJECT_ROOT/.env" ]]; then
  set -a
  # shellcheck disable=SC1090
  source "$PROJECT_ROOT/.env"
  set +a
elif [[ -n "${REPO_ROOT:-}" && -f "$REPO_ROOT/.env" ]]; then
  set -a
  # shellcheck disable=SC1090
  source "$REPO_ROOT/.env"
  set +a
fi

# Configuration
NAMESPACE="${NAMESPACE:-besu-network}"
FIREFLY_API_URL="${FIREFLY_API_URL:-http://firefly-api.firefly.svc.cluster.local:5000}"
BESU_RPC_URL="${BESU_RPC_URL:-http://besu-rpc-service:8545}"


log_success "Deploying Financial Tokenization Service..."

# Check prerequisites
if ! command -v kubectl &> /dev/null; then
    log_error "Error: kubectl not found"
    exit 1
fi

# Build Docker image (if needed)
if [ "$BUILD_IMAGE" == "true" ]; then
    log_warn "Building Docker image..."
    docker build -t financial-tokenization-service:v1.0.0 "$PROJECT_ROOT/services/financial-tokenization"
fi

# Deploy service
log_warn "Deploying service..."
kubectl apply -f "$PROJECT_ROOT/services/financial-tokenization/k8s/deployment.yaml"

# Wait for service to be ready
log_warn "Waiting for service to be ready..."
kubectl wait --for=condition=ready pod -l app=financial-tokenization-service -n "$NAMESPACE" --timeout=300s

log_success "Financial Tokenization Service deployed successfully!"
log_warn "Service URL: http://financial-tokenization-service.$NAMESPACE.svc.cluster.local:8080"

