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

cd "$(dirname "$0")/.."
if [[ -f scripts/load-secrets.sh ]]; then
  # Export secrets from creds/secrets.env (dotenv) when available.
  source scripts/load-secrets.sh
fi

# Prefer repo-local kubeconfig if present and KUBECONFIG is not set.
if [[ -z "${KUBECONFIG:-}" && -f creds/kubeconfig.yaml ]]; then
  export KUBECONFIG="$(pwd)/creds/kubeconfig.yaml"
fi

source deploy/env.sh

if [[ ! -f deploy/.last-image ]]; then
  echo "deploy/.last-image puuttuu. Aja ensin ./deploy/build.sh"
  exit 1
fi

# Default env selection: DEPLOY_TARGET=staging|prod (fallback staging) to avoid manual export
if [[ -z "${K8S_NAMESPACE:-}" || -z "${APP_HOST:-}" || -z "${NEXT_PUBLIC_SITE_URL:-}" || -z "${NEXT_PUBLIC_API_BASE:-}" || -z "${APP_ENV:-}" || -z "${CLUSTER_ISSUER:-}" || -z "${INGRESS_CLASS:-}" ]]; then
  TARGET="${DEPLOY_TARGET:-${TARGET:-staging}}"
  case "$TARGET" in
    prod|production)
      K8S_NAMESPACE="${K8S_NAMESPACE:-$PROD_NAMESPACE}"
      APP_HOST="${APP_HOST:-$PROD_HOST}"
      API_HOST="${API_HOST:-$PROD_HOST}"
      NEXT_PUBLIC_SITE_URL="${NEXT_PUBLIC_SITE_URL:-https://$APP_HOST}"
      NEXT_PUBLIC_API_BASE="${NEXT_PUBLIC_API_BASE:-https://$API_HOST/api}"
      APP_ENV="${APP_ENV:-production}"
      CLUSTER_ISSUER="${CLUSTER_ISSUER:-$PROD_CLUSTER_ISSUER}"
      ;;
    test|testing)
      K8S_NAMESPACE="${K8S_NAMESPACE:-$TEST_NAMESPACE}"
      APP_HOST="${APP_HOST:-$TEST_HOST}"
      API_HOST="${API_HOST:-$TEST_API_HOST:-$TEST_HOST}"
      NEXT_PUBLIC_SITE_URL="${NEXT_PUBLIC_SITE_URL:-https://$APP_HOST}"
      NEXT_PUBLIC_API_BASE="${NEXT_PUBLIC_API_BASE:-https://$API_HOST/api}"
      APP_ENV="${APP_ENV:-testing}"
      CLUSTER_ISSUER="${CLUSTER_ISSUER:-$TEST_CLUSTER_ISSUER:-$STAGING_CLUSTER_ISSUER}"
      ;;
    staging|stage|stg|*)
      K8S_NAMESPACE="${K8S_NAMESPACE:-$STAGING_NAMESPACE}"
      APP_HOST="${APP_HOST:-$STAGING_HOST}"
      API_HOST="${API_HOST:-$STAGING_HOST}"
      NEXT_PUBLIC_SITE_URL="${NEXT_PUBLIC_SITE_URL:-https://$APP_HOST}"
      NEXT_PUBLIC_API_BASE="${NEXT_PUBLIC_API_BASE:-https://$API_HOST/api}"
      APP_ENV="${APP_ENV:-staging}"
      CLUSTER_ISSUER="${CLUSTER_ISSUER:-$STAGING_CLUSTER_ISSUER}"
      ;;
  esac
  INGRESS_CLASS="${INGRESS_CLASS:-$INGRESS_CLASS}"
  echo "Using target: $TARGET (namespace=$K8S_NAMESPACE host=$APP_HOST env=$APP_ENV)"
fi

: "${K8S_NAMESPACE:?K8S_NAMESPACE pitää asettaa}"
: "${APP_HOST:?APP_HOST pitää asettaa}"
: "${API_HOST:=${APP_HOST}}"
: "${NEXT_PUBLIC_SITE_URL:?NEXT_PUBLIC_SITE_URL pitää asettaa}"
: "${NEXT_PUBLIC_API_BASE:?NEXT_PUBLIC_API_BASE pitää asettaa}"
: "${APP_ENV:?APP_ENV pitää asettaa}"
: "${CLUSTER_ISSUER:?CLUSTER_ISSUER pitää asettaa}"
: "${INGRESS_CLASS:?INGRESS_CLASS pitää asettaa}"
: "${APP_REPLICAS:=${APP_REPLICAS:-2}}"

IMAGE=$(cat deploy/.last-image)
K8S_IMAGE="$IMAGE"
APP_VERSION="${APP_VERSION:-$(echo \"$IMAGE\" | awk -F: '{print $NF}')}"

export K8S_NAMESPACE APP_HOST API_HOST NEXT_PUBLIC_SITE_URL NEXT_PUBLIC_API_BASE APP_ENV CLUSTER_ISSUER INGRESS_CLASS APP_REPLICAS K8S_IMAGE APP_VERSION

resolve_database_url() {
  local db_url="${DATABASE_URL:-}"
  if [[ -z "$db_url" ]]; then
    # If DATABASE_URL isn't available locally, try to reuse the in-cluster secret.
    # This prevents "works in cluster but deploy skipped migrations" drift.
    if command -v kubectl >/dev/null 2>&1 && command -v jq >/dev/null 2>&1; then
      if kubectl -n "$K8S_NAMESPACE" get secret lomavuokraus-web-secrets >/dev/null 2>&1; then
        db_url="$(
          kubectl -n "$K8S_NAMESPACE" get secret lomavuokraus-web-secrets -o json \
            | jq -r '.data.DATABASE_URL // empty' \
            | base64 -d 2>/dev/null || true
        )"
      fi
    fi
  fi

  echo "$db_url"
}

prisma_preflight() {
  local db_url="$1"
  if [[ -z "$db_url" ]]; then
    echo "DATABASE_URL unavailable; skipping Prisma status preflight" >&2
    return 0
  fi

  echo "Prisma preflight: checking migration status for APP_ENV=$APP_ENV (namespace=$K8S_NAMESPACE)"
  if ! DATABASE_URL="$db_url" npx prisma migrate status >/dev/null; then
    echo "Prisma migrate status failed. Fix migration history before deploying." >&2
    exit 1
  fi
}

maybe_run_prisma_migrations() {
  local db_url="$1"
  if [[ -n "$db_url" ]]; then
    echo "Running Prisma migrations for APP_ENV=$APP_ENV (namespace=$K8S_NAMESPACE)"
    DATABASE_URL="$db_url" npx prisma migrate deploy
  else
    echo "DATABASE_URL not set and lomavuokraus-web-secrets/DATABASE_URL not found; skipping Prisma migrations" >&2
  fi
}

DB_URL_FOR_DEPLOY="$(resolve_database_url)"
prisma_preflight "$DB_URL_FOR_DEPLOY"
maybe_run_prisma_migrations "$DB_URL_FOR_DEPLOY"

TMP_MANIFEST=$(mktemp)
envsubst < k8s/app.yaml > "$TMP_MANIFEST"

echo "Applying manifest to namespace: $K8S_NAMESPACE"
kubectl apply -f "$TMP_MANIFEST"

echo "Waiting for rollout..."
kubectl rollout status deployment/"$DEPLOYMENT_NAME" -n "$K8S_NAMESPACE"

rm "$TMP_MANIFEST"

echo "Deploy OK."
