# syntax=docker/dockerfile:1.6
# ---- Build stage (Debian, plus robuste que alpine pour npm)
FROM node:22-bookworm-slim AS build
WORKDIR /app

# NPM moins bavard + moins de trucs qui cassent en CI
ENV npm_config_update_notifier=false \
    npm_config_audit=false \
    npm_config_fund=false \
    npm_config_progress=false

# (Optionnel mais propre) git + certificats
RUN apt-get -o Acquire::Retries=5 -o Acquire::ForceIPv4=true update \
 && apt-get install -y --no-install-recommends ca-certificates git \
 && rm -rf /var/lib/apt/lists/*

# Déps d’abord (cache Docker)
COPY package.json package-lock.json ./
RUN npm ci --no-audit --no-fund

# Sources
COPY . .

# Variables publiques injectées au build (import.meta.env.PUBLIC_*)
ARG PUBLIC_GITEA_BASE
ARG PUBLIC_GITEA_OWNER
ARG PUBLIC_GITEA_REPO

# ✅ Canonical + sitemap base (astro.config.mjs lit process.env.PUBLIC_SITE)
ARG PUBLIC_SITE

# ✅ Garde-fou : si 1 → build fail si PUBLIC_SITE absent
ARG REQUIRE_PUBLIC_SITE=0

ENV PUBLIC_GITEA_BASE=$PUBLIC_GITEA_BASE \
    PUBLIC_GITEA_OWNER=$PUBLIC_GITEA_OWNER \
    PUBLIC_GITEA_REPO=$PUBLIC_GITEA_REPO \
    PUBLIC_SITE=$PUBLIC_SITE \
    REQUIRE_PUBLIC_SITE=$REQUIRE_PUBLIC_SITE

# ✅ antifragile : refuse de builder sans PUBLIC_SITE quand on l’exige
RUN node -e "if (process.env.REQUIRE_PUBLIC_SITE==='1' && !process.env.PUBLIC_SITE) { console.error('FATAL: PUBLIC_SITE is required (canonical/sitemap).'); process.exit(1) }"

# Build Astro (postbuild tourne via npm scripts)
RUN npm run build

# ---- Runtime stage (nginx)
FROM nginx:1.27-alpine AS runtime
COPY nginx.conf /etc/nginx/conf.d/default.conf
COPY --from=build /app/dist/ /usr/share/nginx/html/
RUN find /usr/share/nginx/html -type d -exec chmod 755 {} \; \
 && find /usr/share/nginx/html -type f -exec chmod 644 {} \;
EXPOSE 80