# Multi-stage build for production
FROM node:18-alpine AS frontend-build

WORKDIR /app/frontend
COPY package*.json ./
RUN npm ci --only=production

COPY . .
RUN npm run build

# Backend build stage
FROM node:18-alpine AS backend-build

WORKDIR /app/backend
COPY package*.json ./
RUN npm ci --only=production

COPY server/ ./server/
COPY package.json ./

# Production stage
FROM node:18-alpine AS production

WORKDIR /app

# Install backend dependencies
COPY package*.json ./
RUN npm ci --only=production && npm cache clean --force

# Copy backend files
COPY server/ ./server/

# Copy built frontend files
COPY --from=frontend-build /app/dist ./public

# Create uploads directory
RUN mkdir -p uploads

# Create non-root user
RUN addgroup -g 1001 -S nodejs && \
    adduser -S nodejs -u 1001

# Change ownership of app directory
RUN chown -R nodejs:nodejs /app
USER nodejs

EXPOSE 3001

CMD ["node", "server/index.js"]