# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# Use a multi-stage docker build to limit production dependencies.

# Stage 0: Compile the app (needs dev dependencies)
FROM node:24 AS app-build

# Create and change to the app directory.
WORKDIR /usr/src/app

# Copy application dependency manifests to the container image.
# A wildcard is used to ensure copying both package.json AND package-lock.json (when available).
# Copying this first prevents re-running npm install on every code change.
COPY package*.json ./

# Install build dependencies.
RUN npm ci

# Now copy all the code so we can compile
COPY . ./

# compile .ts files into build/
RUN npm run compile

# remove installed node_modules because we will only have production
# dependencies in the final image
RUN rm -rf node_modules/

# Stage 1: Install only production dependencies
FROM node:24 AS node-deps

# Create and change to the app directory.
WORKDIR /usr/src/app

COPY package*.json ./
RUN npm ci --only=production

# Stage 2: Create the final image with only the compiled code and production dependencies
# as we cannot run npm from this image
FROM gcr.io/distroless/nodejs24-debian13:latest

# Create and change to the app directory.
WORKDIR /usr/src/app

COPY package*.json ./
COPY --from=app-build /usr/src/app/build build
COPY --from=node-deps /usr/src/app/node_modules node_modules

ENV NODE_ENV=production

# Run the web service on container startup.
CMD [ "./build/src/index.js"]
