# Base image with Node 22
FROM 086679231553.dkr.ecr.us-east-1.amazonaws.com/docker-parent-images:lambda-node22 AS base

# Install yarn globally
RUN npm install -g yarn@latest && npm install -g typescript

# Copy config and dependency files
COPY .npmrc package.json yarn.lock tsconfig.json tsconfig.build.json ./

# Install production dependencies
RUN --mount=type=secret,id=GITHUB_NPM_TOKEN,required=true,uid=1010 GITHUB_NPM_TOKEN=$(cat /run/secrets/GITHUB_NPM_TOKEN) yarn install --ignore-optional

# Build stage with source code
FROM base AS build
COPY src ./src

# Re-run yarn to ensure correct dependencies in case any are required by src
RUN --mount=type=secret,id=GITHUB_NPM_TOKEN,required=true,uid=1010 GITHUB_NPM_TOKEN=$(cat /run/secrets/GITHUB_NPM_TOKEN) yarn build

# Final runtime image
FROM 086679231553.dkr.ecr.us-east-1.amazonaws.com/docker-parent-images:lambda-node22 AS runner

ARG GIT_COMMIT
ARG REPOSITORY_URL
ARG VERSION

# Add Datadog Lambda extension
COPY --from=public.ecr.aws/datadog/lambda-extension:83 /opt/. /opt/

# Add Sentry Lambda extension
COPY --from=public.ecr.aws/sentry/sentry-node-serverless-sdk:28 /opt/ /opt

# Copy built production dependencies
COPY --from=base  /var/task/node_modules ./node_modules

# Copy the built application code
COPY --from=build /var/task ./

# Set Lambda handler environment variable
ENV DD_LAMBDA_HANDLER=app.handler

# Configure datadog environment variables
ENV DD_VERSION=$VERSION
ENV DD_GIT_REPOSITORY_URL=$REPOSITORY_URL
ENV DD_GIT_COMMIT_SHA=$GIT_COMMIT

#Entrypoint for the Lambda function
CMD [ "node_modules/datadog-lambda-js/dist/handler.handler" ]
