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

cd "$(dirname "$0")/.."
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}"
      NEXT_PUBLIC_SITE_URL="${NEXT_PUBLIC_SITE_URL:-https://$PROD_HOST}"
      NEXT_PUBLIC_API_BASE="${NEXT_PUBLIC_API_BASE:-https://$PROD_HOST/api}"
      APP_ENV="${APP_ENV:-production}"
      CLUSTER_ISSUER="${CLUSTER_ISSUER:-$PROD_CLUSTER_ISSUER}"
      ;;
    staging|stage|stg|*)
      K8S_NAMESPACE="${K8S_NAMESPACE:-$STAGING_NAMESPACE}"
      APP_HOST="${APP_HOST:-$STAGING_HOST}"
      NEXT_PUBLIC_SITE_URL="${NEXT_PUBLIC_SITE_URL:-https://$STAGING_HOST}"
      NEXT_PUBLIC_API_BASE="${NEXT_PUBLIC_API_BASE:-https://$STAGING_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}"
: "${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}"

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

export K8S_NAMESPACE APP_HOST NEXT_PUBLIC_SITE_URL NEXT_PUBLIC_API_BASE APP_ENV CLUSTER_ISSUER INGRESS_CLASS K8S_IMAGE APP_VERSION

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."
