# Use Node.js 20 as base image
FROM node:20-alpine

# Set working directory
WORKDIR /app

# Install system dependencies
RUN apk add --no-cache git

# Copy package files
COPY package*.json ./
COPY tournament-frontend/package*.json ./tournament-frontend/

# Install dependencies
RUN npm ci
RUN cd tournament-frontend && npm ci

# Copy application code
COPY . .

# Build the frontend
RUN cd tournament-frontend && npm run build

# Copy built frontend to backend public directory
RUN mkdir -p public && cp -r tournament-frontend/build/* public/

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

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

# Expose port
EXPOSE 4000

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

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