# Script de build pour la production
# Usage: .\scripts\build_production.ps1

param(
    [string]$Platform = "apk",  # apk, appbundle, ios, web
    [switch]$Clean = $false
)

Write-Host "🚀 Build AfterWork pour la production..." -ForegroundColor Cyan
Write-Host "   Plateforme: $Platform" -ForegroundColor Gray

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

# Nettoyage si demandé
if ($Clean) {
    Write-Host "`n🧹 Nettoyage du projet..." -ForegroundColor Yellow
    flutter clean
    flutter pub get
}

# Définir les dart-defines
$dartDefines = @(
    "API_BASE_URL=$API_BASE_URL",
    "ENVIRONMENT=$ENVIRONMENT"
)

$dartDefineArgs = $dartDefines | ForEach-Object { "--dart-define=$_" }

Write-Host "`n📝 Configuration:" -ForegroundColor Yellow
Write-Host "   API_BASE_URL: $API_BASE_URL" -ForegroundColor Gray
Write-Host "   ENVIRONMENT: $ENVIRONMENT" -ForegroundColor Gray

# Build selon la plateforme
Write-Host "`n🔨 Build en cours..." -ForegroundColor Yellow

switch ($Platform.ToLower()) {
    "apk" {
        Write-Host "   Création de l'APK..." -ForegroundColor Gray
        flutter build apk @dartDefineArgs --release
        $outputPath = "build\app\outputs\flutter-apk\app-release.apk"
    }
    "appbundle" {
        Write-Host "   Création de l'App Bundle..." -ForegroundColor Gray
        flutter build appbundle @dartDefineArgs --release
        $outputPath = "build\app\outputs\bundle\release\app-release.aab"
    }
    "ios" {
        Write-Host "   Création de l'IPA iOS..." -ForegroundColor Gray
        flutter build ios @dartDefineArgs --release
        $outputPath = "build\ios\ipa"
    }
    "web" {
        Write-Host "   Création du build Web..." -ForegroundColor Gray
        flutter build web @dartDefineArgs --release
        $outputPath = "build\web"
    }
    default {
        Write-Host "   ❌ Plateforme non supportée: $Platform" -ForegroundColor Red
        Write-Host "   Plateformes disponibles: apk, appbundle, ios, web" -ForegroundColor Yellow
        exit 1
    }
}

# Vérifier le succès du build
if ($LASTEXITCODE -eq 0) {
    Write-Host "`n✅ Build terminé avec succès!" -ForegroundColor Green
    Write-Host "`n📦 Fichier de sortie:" -ForegroundColor Cyan
    Write-Host "   $outputPath" -ForegroundColor White

    if (Test-Path $outputPath) {
        $size = (Get-Item $outputPath -ErrorAction SilentlyContinue | Measure-Object -Property Length -Sum).Sum
        if ($size) {
            $sizeMB = [math]::Round($size / 1MB, 2)
            Write-Host "   Taille: $sizeMB MB" -ForegroundColor Gray
        }
    }
} else {
    Write-Host "`n❌ Le build a échoué!" -ForegroundColor Red
    exit 1
}
