# Stage 1: Build Frontend
FROM node:20-alpine AS frontend-builder

WORKDIR /app/frontend

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

# Install all dependencies (including devDependencies for build)
# Use npm install which works without lockfile
RUN npm install

# Copy frontend source and build
COPY frontend/ ./
RUN npm run build

# Stage 2: Build Backend
FROM node:20-alpine AS backend-builder

WORKDIR /app/backend

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

# Install all dependencies (including TypeScript)
RUN npm install

# Copy backend source and compile TypeScript
COPY backend/ ./
RUN npm run build

# Stage 3: Production Runtime
FROM node:20-alpine

# Upgrade existing packages to fix base image vulnerabilities, 
# then install su-exec and shadow (for usermod/groupmod)
RUN apk upgrade --no-cache && \
    apk add --no-cache su-exec shadow

WORKDIR /app

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

# Install production dependencies only
RUN npm install --omit=dev && \
    npm cache clean --force

# Copy compiled backend from builder
COPY --from=backend-builder /app/backend/dist ./dist

# Copy built frontend into public directory for Express to serve
COPY --from=frontend-builder /app/frontend/dist ./dist/public

# Create temp upload directory
RUN mkdir -p /app/temp

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

# Environment variables (Unraid defaults and App defaults)
ENV PUID=99 \
    PGID=100 \
    TZ=UTC \
    NODE_ENV=production \
    PORT=3000 \
    MAX_FILE_SIZE=10485760 \
    TEMP_DIR=/app/temp

# Expose port
EXPOSE 3000

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

ENTRYPOINT ["docker-entrypoint.sh"]

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