FROM node:20-alpine

WORKDIR /app

# Copy package files and install dependencies
COPY package*.json ./
RUN npm ci

# Copy only the necessary files for the backend
COPY app.js ./
COPY src/api ./src/api
COPY src/utils ./src/utils
COPY src/types.ts ./src/types.ts

# Create script to handle environment variables
RUN echo '#!/bin/sh\n\
if [ ! -f .env ] && [ -n "$WREN_API_TOKEN" ]; then\n\
  echo "Creating .env file from environment variables..."\n\
  echo "WREN_API_TOKEN=$WREN_API_TOKEN" > .env\n\
fi\n\
\n\
exec "$@"' > /entrypoint.sh \
&& chmod +x /entrypoint.sh

# Use our entrypoint script before running the app
ENTRYPOINT ["/entrypoint.sh"]
CMD ["node", "app.js"]
