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

# ── Config ────────────────────────────────────────────────────────────────────
ENV_FILE="env/prod.json"
OUTPUT_DIR="build/outputs"
APK_SRC="build/app/outputs/flutter-apk/app-release.apk"
APK_DEST="$OUTPUT_DIR/rentaldrivego-release.apk"

# ── Checks ────────────────────────────────────────────────────────────────────
cd "$(dirname "$0")"

if ! command -v flutter &>/dev/null; then
  echo "❌  flutter not found in PATH"
  exit 1
fi

if [[ ! -f "$ENV_FILE" ]]; then
  echo "❌  $ENV_FILE not found — create it with production API URLs"
  exit 1
fi

# ── Build ─────────────────────────────────────────────────────────────────────
echo "▶  Cleaning previous build..."
flutter clean

echo "▶  Fetching dependencies..."
flutter pub get

echo "▶  Building release APK (production)..."
flutter build apk --release --dart-define-from-file="$ENV_FILE"

# ── Copy to output ────────────────────────────────────────────────────────────
mkdir -p "$OUTPUT_DIR"
cp "$APK_SRC" "$APK_DEST"

echo ""
echo "✅  Build complete!"
echo "    APK → $APK_DEST"
echo "    Size: $(du -sh "$APK_DEST" | cut -f1)"
