FROM 086679231553.dkr.ecr.us-east-1.amazonaws.com/docker-parent-images:node22 AS prod-deps

# Install pnpm
USER root
RUN         corepack enable pnpm && corepack prepare pnpm@10.11.0 --activate

# Copy app and install production dependencies
WORKDIR     /var/app
COPY        .npmrc package.json pnpm-lock.yaml apollo.config.js tsconfig.json tsconfig.build.json codegen.yml ./

RUN         --mount=type=secret,id=GITHUB_TOKEN,required=true,uid=1000 GITHUB_TOKEN=$(cat /run/secrets/GITHUB_TOKEN) \
            pnpm install --frozen-lockfile --prod


##### dev-deps #####
# Install dev dependencies, and copy in source.
####################
FROM        prod-deps AS dev-deps
RUN         --mount=type=secret,id=GITHUB_TOKEN,required=true,uid=1000 GITHUB_TOKEN=$(cat /run/secrets/GITHUB_TOKEN) \
            pnpm install --frozen-lockfile
COPY        src ./src


##### dev #######
# Run as a hot-reloading service.
#################
FROM        dev-deps AS dev
COPY        nodemon.json ./
ENV         PORT 8080
EXPOSE      8080
ENTRYPOINT  ["pnpm", "start"]


##### lint-and-test #####
# Install unit testing and linting configs
# and configure to run tests
#########################
FROM        dev-deps AS lint-and-test

COPY        biome.json graphql-schema-linter.config.js vitest.config.mts vitest.setup.mts vitest.integration.global-setup.mts ./
COPY        lib ./lib
COPY        tests ./tests

ENTRYPOINT  ["pnpm", "test"]


##### integration-tests #####
# Install unit testing and linting configs
# and configure to run tests
#############################
FROM        lint-and-test AS integration-tests
ENTRYPOINT ["pnpm", "test:integration"]


##### build-artifacts #####
# Build production-ready artifacts
###########################
FROM        dev-deps AS build-artifacts
RUN         --mount=type=secret,id=GITHUB_TOKEN,required=true,uid=1000 GITHUB_TOKEN=$(cat /run/secrets/GITHUB_TOKEN) \
            pnpm build



##### deploy #####
# Grab production node dependencies and
# production build artifacts
# and run as a service.
##################
FROM        086679231553.dkr.ecr.us-east-1.amazonaws.com/docker-parent-images:node22 AS deploy
WORKDIR     /var/app
# Copy production dependencies
COPY        --from=prod-deps --chown=node:node /var/app/node_modules ./node_modules
# Copy build
COPY        --from=build-artifacts --chown=node:node /var/app/build ./

ENV         PORT 8080
EXPOSE      8080
CMD         ["node", "index.js"]
