# Use a specific version of node to ensure consistent builds
FROM node:current-alpine AS builder

# Set environment variables for Node.js
ENV NODE_ENV=production

# Create and set the working directory
WORKDIR /app

# Install system dependencies required for building certain npm packages
# Install git if your npm dependencies require it
RUN apk --no-cache add git

# Copy package.json and package-lock.json (or yarn.lock) first to leverage Docker cache
COPY package*.json ./

# Optionally, if you're using Prisma, copy the Prisma schema file
# This is necessary for the `prisma generate` command
COPY prisma ./prisma/

# Install dependencies, including Prisma if used in your project
RUN npm install --omit=dev

# Install global packages if necessary
RUN npm install -g dotenv-cli

# Build stage for the actual source code
FROM node:current-alpine AS app

WORKDIR /app

# Copy installed node_modules from builder stage
COPY --from=builder /app/node_modules ./node_modules

# Copy the rest of your app's source code from the project root to the container
COPY . .

# Copy over any generated files from the builder stage if necessary
# For example, the prisma client if you're using Prisma
COPY --from=builder /app/node_modules/.prisma/client /app/node_modules/.prisma/client

# Copy the entrypoint script and give it execute permissions
COPY _deploy/entrypoint.sh /usr/local/bin/
COPY _deploy/entrypoint.sh ./
RUN chmod +x /usr/local/bin/entrypoint.sh

# Expose a port (e.g., 3000) to access the app
EXPOSE 3000

# Use the entrypoint script as the entrypoint
ENTRYPOINT ["entrypoint.sh"]

# Start the Next.js app
CMD ["npm", "start"]
