# Build frontend
FROM node:20-alpine AS frontend-builder

WORKDIR /app/frontend

# Configure npm to use legacy peer deps
RUN npm config set legacy-peer-deps true

COPY frontend/package*.json ./
RUN npm ci

COPY frontend/ ./
RUN npm run build

# Build backend and final image
FROM node:20-alpine

# Install MinIO client (detect architecture)
RUN ARCH=$(uname -m | sed 's/x86_64/amd64/g' | sed 's/aarch64/arm64/g') && \
    wget https://dl.min.io/client/mc/release/linux-${ARCH}/mc && \
    chmod +x mc && \
    mv mc /usr/local/bin/

# Install nginx for serving frontend
RUN apk add --no-cache nginx

WORKDIR /app

# Copy backend package files
COPY backend/package*.json ./

# Install build tools for native dependencies
RUN apk add --no-cache python3 make g++

# Install production dependencies
RUN npm ci --only=production

# Rebuild bcrypt
RUN npm rebuild bcrypt --build-from-source

# Copy backend application files
COPY backend/ ./

# Copy frontend build
COPY --from=frontend-builder /app/frontend/build /app/public

# Copy nginx config for combined container
COPY nginx.conf /etc/nginx/http.d/default.conf

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

# Create necessary directories with proper permissions
RUN mkdir -p logs temp /tmp/minio-webui-temp /run/nginx && \
    chown -R nodejs:nodejs /app logs temp /tmp/minio-webui-temp && \
    chown -R nodejs:nodejs /var/lib/nginx /var/log/nginx /run/nginx

# Create startup script
RUN echo '#!/bin/sh' > /app/start.sh && \
    echo 'nginx' >> /app/start.sh && \
    echo 'exec node src/app.js' >> /app/start.sh && \
    chmod +x /app/start.sh

# Switch to non-root user
USER nodejs

# Expose ports (3000 for API, 8080 for frontend)
EXPOSE 3000 8080

# Start both nginx and node
CMD ["/app/start.sh"]
