# Build Stage
FROM node:20-alpine AS builder

# Set working directory
WORKDIR /usr/src/app

# Install dependencies needed for node-gyp and native modules (if any)
RUN apk add --no-cache python3 make g++

# Copy package.json and workspace configuration
COPY package*.json ./
COPY turbo.json ./
COPY tsconfig.json ./

# Copy packages and apps configurations
COPY packages/ packages/
COPY apps/api/package.json apps/api/

# Install all dependencies (workspaces)
RUN npm install

# Copy source code
COPY apps/api/ apps/api/

# Build the API
WORKDIR /usr/src/app/apps/api
RUN npm run build

# Production Stage
FROM node:20-alpine AS production

WORKDIR /usr/src/app

# Set NODE_ENV to production
ENV NODE_ENV=production

# Copy built assets from builder
COPY --from=builder /usr/src/app/package*.json ./
COPY --from=builder /usr/src/app/node_modules ./node_modules
COPY --from=builder /usr/src/app/apps/api/package.json ./apps/api/
COPY --from=builder /usr/src/app/apps/api/dist ./apps/api/dist
COPY --from=builder /usr/src/app/apps/api/node_modules ./apps/api/node_modules

# Expose the API port
EXPOSE 3000

# Start the application
CMD ["node", "apps/api/dist/main"]
