#!/bin/bash
# Script pour générer et vérifier le coverage de tests (T0043)

set -e

# Variables
COVERAGE_DIR="coverage"
COVERAGE_PROFILE="$COVERAGE_DIR/coverage.out"
COVERAGE_HTML="$COVERAGE_DIR/coverage.html"
COVERAGE_JSON="$COVERAGE_DIR/coverage.json"
COVERAGE_THRESHOLD=80

# Déterminer le répertoire de travail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
cd "$PROJECT_ROOT"

# Créer le dossier coverage
mkdir -p "$COVERAGE_DIR"

# Aller dans le répertoire du backend
cd veza-backend-api

# Générer le profile de coverage
echo "Running tests with coverage..."
go test ./... -coverprofile="$COVERAGE_PROFILE" -covermode=atomic -v

# Vérifier que le profile a été généré
if [ ! -f "$COVERAGE_PROFILE" ]; then
    echo "ERROR: Coverage profile not generated"
    exit 1
fi

# Générer le rapport HTML
echo "Generating HTML report..."
go tool cover -html="$COVERAGE_PROFILE" -o "$COVERAGE_HTML"

# Générer un rapport JSON (format simple)
echo "Generating coverage summary..."
COVERAGE_SUMMARY=$(go tool cover -func="$COVERAGE_PROFILE" | grep total | awk '{print $3}' | sed 's/%//')
echo "{\"coverage_percent\": $COVERAGE_SUMMARY, \"threshold\": $COVERAGE_THRESHOLD}" > "$COVERAGE_JSON" 2>/dev/null || true

# Calculer le pourcentage de coverage (entier)
COVERAGE_PERCENT=$(go tool cover -func="$COVERAGE_PROFILE" | grep total | awk '{print $3}' | sed 's/%//' | cut -d. -f1)

echo ""
echo "================================================"
echo "Coverage Summary"
echo "================================================"
go tool cover -func="$COVERAGE_PROFILE" | tail -1
echo ""
echo "Total coverage: ${COVERAGE_PERCENT}%"
echo "Threshold: ${COVERAGE_THRESHOLD}%"
echo "HTML report: $COVERAGE_DIR/coverage.html"
echo "================================================"
echo ""

# Vérifier le seuil
if [ "$COVERAGE_PERCENT" -lt "$COVERAGE_THRESHOLD" ]; then
    echo "ERROR: Coverage ${COVERAGE_PERCENT}% is below threshold ${COVERAGE_THRESHOLD}%"
    exit 1
fi

echo "✅ Coverage check passed!"
exit 0

