#!/usr/bin/env bash
# Rebreak Native — EAS Cloud-Build + Store-Submit für Release-Channels.
#
# Usage:
#   ./eas-release.sh                    # iOS only (build + TestFlight) — Default
#   ./eas-release.sh --ios              # iOS only
#   ./eas-release.sh --android          # Android AAB + Play-Console Internal
#   ./eas-release.sh --both             # iOS + Android parallel
#   ./eas-release.sh --build-only       # nur Build, kein Submit (für QA)
#   ./eas-release.sh --no-wait          # Build im Hintergrund, return sofort
#
# Profile: `production` (live in eas.json — staging-Backend, app-bundle, m-medium)
#
# Voraussetzungen:
#   - `eas login` einmalig durchgeführt
#   - Android: serviceAccountKeyPath in eas.json gesetzt (Play-Console-Submit)
#   - iOS: Apple-Connect-Login wird beim ersten Run abgefragt
#   - Vorher version-bumpen (package.json + android/app/build.gradle + iOS Info.plist)
set -euo pipefail

cd "$(dirname "$0")"

PROFILE="production"
PLATFORM="ios"
SUBMIT_FLAG="--auto-submit"
WAIT_FLAG=""

while [[ $# -gt 0 ]]; do
  case "$1" in
    --ios)         PLATFORM="ios"; shift ;;
    --android)     PLATFORM="android"; shift ;;
    --both)        PLATFORM="all"; shift ;;
    --build-only)  SUBMIT_FLAG=""; shift ;;
    --no-wait)     WAIT_FLAG="--no-wait"; shift ;;
    -h|--help)
      awk '/^#!/{next} /^#/{sub(/^# ?/, ""); print; next} {exit}' "$0"
      exit 0 ;;
    *) echo "Unbekanntes Flag: $1"; echo "  --help für Hilfe"; exit 1 ;;
  esac
done

if ! command -v eas >/dev/null 2>&1; then
  echo "eas-cli nicht gefunden. Install:"
  echo "  pnpm add -g eas-cli"
  exit 1
fi

echo "→ EAS Build — platform=$PLATFORM profile=$PROFILE submit=${SUBMIT_FLAG:-no}"
echo ""
echo "  Bevor du fortfährst: Version gebumpt?"
echo "    - apps/rebreak-native/package.json (version)"
echo "    - android/app/build.gradle (versionCode + versionName)"
echo "    - ios/ReBreak/Info.plist (CFBundleVersion + CFBundleShortVersionString)"
echo ""
read -p "Versionen sind aktuell? [y/N] " -n 1 -r
echo ""
[[ ! $REPLY =~ ^[Yy]$ ]] && { echo "Abgebrochen."; exit 0; }

eas build \
  --platform "$PLATFORM" \
  --profile "$PROFILE" \
  --non-interactive \
  $SUBMIT_FLAG \
  $WAIT_FLAG

echo ""
echo "Fertig."
echo ""
if [[ -n "$SUBMIT_FLAG" ]]; then
  echo "Submit läuft automatisch nach Build:"
  echo "  - iOS  → TestFlight (App Store Connect)"
  echo "  - Android → Play Console Internal-Track"
  echo ""
  echo "Status checken:  eas build:list --limit 5"
fi
