FROM node:18-alpine

WORKDIR /app

# Copy package files
COPY package*.json ./

# Install dependencies
RUN npm install

# Install git and tools required for healthchecks and HTTPS clones
RUN apk add --no-cache git curl ca-certificates openssh-client && update-ca-certificates

# Copy source code
COPY . .

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

# Create git-repos directory and set proper permissions
RUN mkdir -p /app/git-repos /app/git-repos/diffs
RUN chown -R git-integration:nodejs /app
RUN chmod -R 755 /app/git-repos

# Create entrypoint script to handle volume permissions
RUN echo '#!/bin/sh' > /app/entrypoint.sh && \
    echo '# Fix volume mount permissions' >> /app/entrypoint.sh && \
    echo 'echo "🔧 Fixing git-repos directory permissions..."' >> /app/entrypoint.sh && \
    echo 'mkdir -p /app/git-repos/diffs' >> /app/entrypoint.sh && \
    echo 'chown -R git-integration:nodejs /app/git-repos 2>/dev/null || echo "⚠️  Could not change ownership (expected in some environments)"' >> /app/entrypoint.sh && \
    echo 'chmod -R 755 /app/git-repos 2>/dev/null || echo "⚠️  Could not change permissions (expected in some environments)"' >> /app/entrypoint.sh && \
    echo 'echo "✅ Directory setup completed"' >> /app/entrypoint.sh && \
    echo 'echo "📁 Directory listing:"' >> /app/entrypoint.sh && \
    echo 'ls -la /app/git-repos/ 2>/dev/null || echo "Could not list directory"' >> /app/entrypoint.sh && \
    echo '# Switch to git-integration user and execute command' >> /app/entrypoint.sh && \
    echo 'echo "🚀 Starting git-integration service as user git-integration..."' >> /app/entrypoint.sh && \
    echo 'exec su-exec git-integration "$@"' >> /app/entrypoint.sh && \
    chmod +x /app/entrypoint.sh

# Install su-exec for user switching
RUN apk add --no-cache su-exec

# Keep running as root for entrypoint, will switch to git-integration user in entrypoint

# Expose port
EXPOSE 8012

# Health check
HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \
  CMD curl -f http://localhost:8012/health || exit 1

# Start the application
ENTRYPOINT ["/app/entrypoint.sh"]
CMD ["npm", "start"]
