# ── Stage 1: frontend build ─────────────────────────────────────────────
FROM node:22-alpine AS frontend-build
WORKDIR /work
RUN corepack enable && corepack prepare pnpm@9.15.0 --activate
COPY frontend/package.json frontend/pnpm-lock.yaml ./frontend/
RUN cd frontend && pnpm install --frozen-lockfile
COPY frontend/ ./frontend/
RUN cd frontend && pnpm build
# frontend/dist is written to /work/src/VolcanicCore.Api/wwwroot via vite.config outDir,
# but during the build the src/ path doesn't exist yet — so we override outDir on the CLI.
# Actually vite.config uses relative '../src/...' — inside stage 1 that path doesn't exist.
# Rebuild with explicit output:
RUN cd frontend && pnpm exec vite build --outDir /work/wwwroot --emptyOutDir

# ── Stage 2: backend build ──────────────────────────────────────────────
FROM mcr.microsoft.com/dotnet/sdk:9.0 AS backend-build
WORKDIR /work
COPY global.json VolcanicCore.sln ./
COPY src/ ./src/
COPY tests/ ./tests/
# Copy the frontend build into wwwroot so it's part of the published output
COPY --from=frontend-build /work/wwwroot ./src/VolcanicCore.Api/wwwroot
RUN dotnet publish src/VolcanicCore.Api/VolcanicCore.Api.csproj -c Release -o /out

# ── Stage 3: nats-server binary from official image ─────────────────────
# Grab the pinned binary out of the official nats image instead of downloading
# from GitHub — the direct download failed under Coolify's builder network.
FROM nats:2.10.22-alpine AS nats-fetch

# ── Stage 4: runtime ────────────────────────────────────────────────────
FROM mcr.microsoft.com/dotnet/aspnet:9.0
RUN useradd -u 1000 -m vc
COPY --from=backend-build /out /app
COPY --from=nats-fetch /usr/local/bin/nats-server /usr/local/bin/nats-server
RUN mkdir -p /var/lib/volcaniccore && chown -R vc:vc /var/lib/volcaniccore
ENV STATE_DIR=/var/lib/volcaniccore \
    PORT_ADMIN=8080 \
    PORT_NATS_WS=8081 \
    NATS_SERVER_PATH=/usr/local/bin/nats-server
USER vc
EXPOSE 8080 8081
WORKDIR /app
ENTRYPOINT ["dotnet", "/app/VolcanicCore.Api.dll"]
