# CMS Dockerfile for Placebo.mk Strapi CMS

# Build stage
FROM node:20-alpine AS builder

WORKDIR /app

# Copy package files
COPY package.json package-lock.json* ./

# Install dependencies
RUN npm install --legacy-peer-deps

# Copy source code
COPY . .

# Build Strapi
RUN npm run build

# Prune devDependencies after build (suppress warning)
RUN npm prune --omit=dev

# Production stage
FROM node:20-alpine

WORKDIR /app

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

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

# Copy built application from builder stage
COPY --from=builder --chown=nodejs:nodejs /app/dist ./dist
COPY --from=builder --chown=nodejs:nodejs /app/dist/config ./config
COPY --from=builder --chown=nodejs:nodejs /app/src ./src
COPY --from=builder --chown=nodejs:nodejs /app/public ./public
COPY --from=builder --chown=nodejs:nodejs /app/favicon.png ./favicon.png
COPY --from=builder --chown=nodejs:nodejs /app/.strapi ./.strapi
COPY --from=builder --chown=nodejs:nodejs /app/node_modules ./node_modules
COPY --from=builder --chown=nodejs:nodejs /app/package*.json ./

# Copy entrypoint script
COPY docker-entrypoint.sh /usr/local/bin/
RUN chmod +x /usr/local/bin/docker-entrypoint.sh

# Create the directory structure Strapi expects for the admin build
RUN mkdir -p /app/node_modules/@strapi/admin/dist/server/server && \
    ln -sf /app/dist/build /app/node_modules/@strapi/admin/dist/server/server/build && \
    chown -R nodejs:nodejs /app/node_modules/@strapi/admin

# Create data and database directories with proper permissions
RUN mkdir -p /app/.tmp /app/database /app/database/migrations /app/public/uploads && \
    chown -R nodejs:nodejs /app

# Don't switch to nodejs user yet - entrypoint will handle it
# USER nodejs

# Health check
HEALTHCHECK --interval=30s --timeout=3s --start-period=60s --retries=3 \
  CMD node -e "require('http').get('http://localhost:1337/_health', (r) => {if(r.statusCode !== 200) process.exit(1)})"

# Expose port
EXPOSE 1337

# Use entrypoint to fix permissions on startup then switch to nodejs user
ENTRYPOINT ["docker-entrypoint.sh"]

# Start Strapi
CMD ["npm", "run", "start"]
