# Build stage
FROM node:14 AS build

WORKDIR /app

# Copy package.json and package-lock.json
COPY .env ./.env
COPY package*.json ./
COPY client/package*.json ./client/
COPY server/package*.json ./server/

# Install dependencies
RUN cd client && npm cache clean --force && rm -rf node_modules && npm install
RUN cd server && npm install

# Copy source code
COPY . .

# Install nodemailer and dotenv
RUN npm install nodemailer dotenv date-fns react-icons

# Build client
RUN cd client && npm run build

# Install all dependencies including devDependencies
RUN cd server && npm install

# Build server
RUN cd server && npm run build

# Remove devDependencies
RUN cd server && npm prune --production

# Production stage
FROM node:14-alpine

WORKDIR /app

# Copy built assets from build stage
COPY --from=build /app/client/build ./client/build
COPY --from=build /app/server ./server
COPY --from=build /app/.env ./.env

# Set working directory to server
WORKDIR /app/server

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

# Expose port
EXPOSE 5000

# Start the server
CMD ["npm", "start"]