FROM node:18-alpine

WORKDIR /app

# Install system dependencies including FFmpeg
RUN apk add --no-cache \
    ffmpeg \
    curl \
    bash \
    && rm -rf /var/cache/apk/*

# Create app user for security
RUN addgroup -S appgroup && \
    adduser -S appuser -G appgroup

# Copy package files
COPY package*.json ./
RUN npm install

# Copy source code
COPY . .

# Install ts-node globally for development
RUN npm install -g ts-node typescript

# Create necessary directories
RUN mkdir -p /tmp/video-processing && \
    mkdir -p /app/ssl/ && \
    mkdir -p /app/public/uploads

# Ensure SSL directory exists and copy files properly
RUN if [ -d "./ssl" ]; then \
        echo "SSL directory found, copying files..."; \
        cp -r ./ssl/* /app/ssl/ 2>/dev/null || true; \
        ls -la /app/ssl/; \
    else \
        echo "SSL directory not found in build context"; \
        ls -la ./; \
    fi

# Set proper permissions
RUN chown -R appuser:appgroup /app && \
    chmod -R 755 /app

# Switch to non-root user
USER appuser


# Ensure SSL directory exists and copy files properly
RUN mkdir -p /app/ssl/
RUN if [ -d "./ssl" ]; then \
        echo "SSL directory found, copying files..."; \
        cp -r ./ssl/* /app/ssl/ 2>/dev/null || true; \
        ls -la /app/ssl/; \
    else \
        echo "SSL directory not found in build context"; \
        ls -la ./; \
    fi


# Set environment variables
ENV NODE_ENV=production
ENV PORT=9000

EXPOSE 9000

# Health check
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
  CMD curl -f https://api.vzzpr.thesuitchstaging2.com:9000/api/v1/video/health || exit 1
# Use dev command for local development
CMD ["npm", "run", "dev"]