# Use Node.js 18.3 as the base image
FROM node:20-slim AS build

# Install Python and build tools for node-gyp
RUN apt-get update && \
    apt-get install -y python3 make g++ && \
    ln -s /usr/bin/python3 /usr/bin/python && \
    apt-get clean && \
    rm -rf /var/lib/apt/lists/*

# Create app directory
ENV APP_DIR=/usr/src/app/
RUN mkdir -p ${APP_DIR}

# Install global dependencies like pm2, ts-node, and typescript as root
RUN npm install -g pm2 ts-node typescript
    
# Create a non-root user and switch to it
ENV APP_USER=appuser
RUN adduser --disabled-password --gecos '' ${APP_USER}
WORKDIR ${APP_DIR}
RUN chown -R ${APP_USER}:${APP_USER} ${APP_DIR}

# Switch to non-root user before copying files and installing dependencies
USER ${APP_USER}

# Copy package.json and package-lock.json and install dependencies as appuser
COPY --chown=${APP_USER}:${APP_USER} package.json package-lock.json ./
RUN npm install

# Copy the rest of the application code with appropriate ownership
COPY --chown=${APP_USER}:${APP_USER} . .

# Rebuild bcrypt and other native dependencies as appuser
RUN npm rebuild bcrypt --build-from-source

# Build the application using the npm script, assuming "build:ts" is defined
RUN npm run build:ts

# Environment variables
ENV CI=true
ENV PORT=14000
ENV NODE_ENV=production

# Expose the application's port
EXPOSE ${PORT}

# Command to run the application using npm start
CMD ["npm", "start"]
