####
# Dockerfile de production pour UnionFlow Server (Backend)
# Build depuis la racine du monorepo
####

## Stage 1 : Build avec Maven
FROM maven:3.9.6-eclipse-temurin-17 AS builder

WORKDIR /app

# Copier tous les POMs du monorepo
COPY pom.xml .
COPY unionflow-server-api/pom.xml unionflow-server-api/
COPY unionflow-server-impl-quarkus/pom.xml unionflow-server-impl-quarkus/

# Télécharger les dépendances
RUN mvn dependency:go-offline -B

# Copier le code source
COPY unionflow-server-api/src unionflow-server-api/src
COPY unionflow-server-impl-quarkus/src unionflow-server-impl-quarkus/src

# Construire l'application
RUN mvn clean package -DskipTests -B -Dquarkus.profile=prod -pl unionflow-server-impl-quarkus -am

## Stage 2 : Image de production
FROM eclipse-temurin:17-jre-alpine

ENV LANGUAGE='en_US:en'
ENV QUARKUS_PROFILE=prod
ENV QUARKUS_HTTP_PORT=8085
ENV QUARKUS_HTTP_HOST=0.0.0.0

# Variables d'environnement pour production
ENV DB_URL=jdbc:postgresql://postgresql-service.postgresql.svc.cluster.local:5432/unionflow
ENV DB_USERNAME=unionflow
ENV DB_PASSWORD=UnionFlow2025!

ENV QUARKUS_OIDC_AUTH_SERVER_URL=https://security.lions.dev/realms/unionflow
ENV QUARKUS_OIDC_CLIENT_ID=unionflow-server
ENV KEYCLOAK_CLIENT_SECRET=unionflow-server-secret-2025
ENV QUARKUS_OIDC_TLS_VERIFICATION=required

ENV CORS_ORIGINS=https://unionflow.lions.dev,https://security.lions.dev
ENV QUARKUS_HTTP_CORS_ORIGINS=${CORS_ORIGINS}

# Installer curl pour health checks
RUN apk add --no-cache curl

# Créer utilisateur non-root
RUN addgroup -g 185 -S appuser && adduser -u 185 -S appuser -G appuser
RUN mkdir -p /app/logs && chown -R appuser:appuser /app/logs

USER appuser

# Copier l'application
COPY --from=builder --chown=appuser:appuser /app/unionflow-server-impl-quarkus/target/quarkus-app/lib/ /deployments/lib/
COPY --from=builder --chown=appuser:appuser /app/unionflow-server-impl-quarkus/target/quarkus-app/*.jar /deployments/
COPY --from=builder --chown=appuser:appuser /app/unionflow-server-impl-quarkus/target/quarkus-app/app/ /deployments/app/
COPY --from=builder --chown=appuser:appuser /app/unionflow-server-impl-quarkus/target/quarkus-app/quarkus/ /deployments/quarkus/

EXPOSE 8085

ENV JAVA_OPTS="-Xmx1g -Xms512m \
    -XX:+UseG1GC \
    -XX:MaxGCPauseMillis=200 \
    -XX:+UseStringDeduplication \
    -Djava.security.egd=file:/dev/./urandom \
    -Dquarkus.profile=${QUARKUS_PROFILE}"

ENTRYPOINT ["sh", "-c", "exec java $JAVA_OPTS -jar /deployments/quarkus-run.jar"]

HEALTHCHECK --interval=30s --timeout=10s --start-period=60s --retries=3 \
  CMD curl -f http://localhost:8085/q/health/ready || exit 1
