#!/bin/bash

# Script de build pour la production
# Usage: ./scripts/build_production.sh [platform] [--clean]
# Platforms: apk, appbundle, ios, web

set -e

# Couleurs pour le terminal
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
CYAN='\033[0;36m'
GRAY='\033[0;90m'
NC='\033[0m' # No Color

# Configuration
PLATFORM="${1:-apk}"
CLEAN=false

# Vérifier les arguments
if [[ "$2" == "--clean" || "$1" == "--clean" ]]; then
    CLEAN=true
fi

# Configuration de production
API_BASE_URL="https://api.lions.dev/afterwork"
ENVIRONMENT="production"

echo -e "${CYAN}🚀 Build AfterWork pour la production...${NC}"
echo -e "${GRAY}   Plateforme: $PLATFORM${NC}"

# Nettoyage si demandé
if [ "$CLEAN" = true ]; then
    echo -e "\n${YELLOW}🧹 Nettoyage du projet...${NC}"
    flutter clean
    flutter pub get
fi

# Dart defines
DART_DEFINES=(
    "--dart-define=API_BASE_URL=$API_BASE_URL"
    "--dart-define=ENVIRONMENT=$ENVIRONMENT"
)

echo -e "\n${YELLOW}📝 Configuration:${NC}"
echo -e "${GRAY}   API_BASE_URL: $API_BASE_URL${NC}"
echo -e "${GRAY}   ENVIRONMENT: $ENVIRONMENT${NC}"

# Build selon la plateforme
echo -e "\n${YELLOW}🔨 Build en cours...${NC}"

case "$PLATFORM" in
    apk)
        echo -e "${GRAY}   Création de l'APK...${NC}"
        flutter build apk "${DART_DEFINES[@]}" --release
        OUTPUT_PATH="build/app/outputs/flutter-apk/app-release.apk"
        ;;
    appbundle)
        echo -e "${GRAY}   Création de l'App Bundle...${NC}"
        flutter build appbundle "${DART_DEFINES[@]}" --release
        OUTPUT_PATH="build/app/outputs/bundle/release/app-release.aab"
        ;;
    ios)
        echo -e "${GRAY}   Création de l'IPA iOS...${NC}"
        flutter build ios "${DART_DEFINES[@]}" --release
        OUTPUT_PATH="build/ios/ipa"
        ;;
    web)
        echo -e "${GRAY}   Création du build Web...${NC}"
        flutter build web "${DART_DEFINES[@]}" --release
        OUTPUT_PATH="build/web"
        ;;
    *)
        echo -e "${RED}   ❌ Plateforme non supportée: $PLATFORM${NC}"
        echo -e "${YELLOW}   Plateformes disponibles: apk, appbundle, ios, web${NC}"
        exit 1
        ;;
esac

# Vérifier le succès du build
if [ $? -eq 0 ]; then
    echo -e "\n${GREEN}✅ Build terminé avec succès!${NC}"
    echo -e "\n${CYAN}📦 Fichier de sortie:${NC}"
    echo -e "   ${OUTPUT_PATH}"

    if [ -e "$OUTPUT_PATH" ]; then
        if [ -f "$OUTPUT_PATH" ]; then
            SIZE=$(du -h "$OUTPUT_PATH" | cut -f1)
            echo -e "${GRAY}   Taille: $SIZE${NC}"
        elif [ -d "$OUTPUT_PATH" ]; then
            SIZE=$(du -sh "$OUTPUT_PATH" | cut -f1)
            echo -e "${GRAY}   Taille: $SIZE${NC}"
        fi
    fi
else
    echo -e "\n${RED}❌ Le build a échoué!${NC}"
    exit 1
fi
