# Use the official Node.js 18 image as the base
ARG ARCH=linux/amd64

FROM --platform=$ARCH node:18

# Set the working directory inside the container
WORKDIR /app

# Install necessary system packages and AWS CLI
RUN apt-get update -y && \
    apt-get install -y \
      libcairo2-dev \
      libpango1.0-dev \
      libjpeg-dev \
      libgif-dev \
      librsvg2-dev \
      curl \
      unzip && \
    # Install AWS CLI
    curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip" && \
    unzip awscliv2.zip && \
    ./aws/install && \
    # Clean up AWS CLI installation files
    rm -rf awscliv2.zip aws && \
    # Clean up apt caches to reduce image size
    apt-get clean && \
    rm -rf /var/lib/apt/lists/*

# Set build-time arguments for AWS credentials
ARG AWS_ACCESS_KEY_ID
ARG AWS_SECRET_ACCESS_KEY
ARG AWS_REGION

# Set environment variables for AWS credentials (available during build and runtime)
ENV AWS_ACCESS_KEY_ID=${AWS_ACCESS_KEY_ID}
ENV AWS_SECRET_ACCESS_KEY=${AWS_SECRET_ACCESS_KEY}
ENV AWS_REGION=${AWS_REGION}
ENV PORT=3000

# Copy the AWS chat script and ensure it is executable
COPY aws-chat.sh .
RUN chmod +x aws-chat.sh && ./aws-chat.sh

# Copy package.json and package-lock.json to leverage Docker caching
COPY package*.json ./

# Install npm dependencies
RUN npm install

# Copy the rest of the application code
COPY . .

# Build the Next.js application
RUN npm run build

# Expose the application's port
EXPOSE 3000

# Start the application in production mode
CMD ["npm", "start"]