# Multi-stage Docker build for BREEDR
# Stage 1: Build frontend
FROM node:18-alpine AS frontend-builder

WORKDIR /app/client

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

# Install frontend dependencies
RUN npm install

# Copy frontend source
COPY client/ ./

# Build frontend for production
RUN npm run build

# Stage 2: Build backend and final image
FROM node:18-alpine AS production

# Install sqlite3 dependencies
RUN apk add --no-cache \
    python3 \
    make \
    g++ \
    sqlite

WORKDIR /app

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

# Install production dependencies
RUN npm install --omit=dev

# Copy server code
COPY server/ ./server/

# Copy built frontend from previous stage
COPY --from=frontend-builder /app/client/dist ./client/dist

# Create necessary directories (including static for branding assets)
RUN mkdir -p /app/data /app/uploads /app/static

# Initialize database schema on build
RUN node server/db/init.js || true

# Set environment variables
ENV NODE_ENV=production
ENV PORT=3000
ENV DB_PATH=/app/data/breedr.db
ENV UPLOAD_PATH=/app/uploads
ENV STATIC_PATH=/app/static

# Expose application port
EXPOSE 3000

# Set up volumes for persistent data
VOLUME ["/app/data", "/app/uploads", "/app/static"]

# Health check
HEALTHCHECK --interval=30s --timeout=10s --start-period=40s --retries=3 \
  CMD node -e "require('http').get('http://localhost:3000/api/health', (r) => {process.exit(r.statusCode === 200 ? 0 : 1)})"

# Start the application
CMD ["node", "server/index.js"]
