ARG NODE_VERSION=22

# Builder stage
FROM node:${NODE_VERSION}-alpine AS builder

WORKDIR /app

# Install necessary build tools
RUN apk add python3 gcc make g++

# Copy package.json and package-lock.json first for efficient caching
COPY package*.json ./

# Install dependencies only if package.json or package-lock.json have changed
RUN npm install

# Copy the rest of the application code
COPY . .

# Build the TypeScript application
RUN npm run build

# Production stage
FROM node:${NODE_VERSION}-alpine

WORKDIR /usr/src/app

# Install just the production dependencies
COPY --from=builder /app/package*.json ./
RUN npm install --only=prod

# Use multi-stage copy to avoid copying unnecessary files
COPY --from=builder /app/task-runner /usr/src/app/task-runner
COPY --from=builder /app/dist /usr/src/app/dist

# Use non-root user for security
RUN addgroup appuser && adduser -S appuser -G appuser && chown -R appuser:appuser /usr/src/app
USER appuser

# Set default ENTRYPOINT and CMD
ENTRYPOINT ["sh", "/usr/src/app/task-runner"]
CMD ["--help"]
