# Stage 1: Dependencies
FROM node:20-alpine AS deps
RUN corepack enable && corepack prepare pnpm@latest --activate
WORKDIR /app

# Copy dependency files
COPY package.json pnpm-lock.yaml ./

# Install dependencies with frozen lockfile
RUN pnpm install --frozen-lockfile

# Stage 2: Builder
FROM node:20-alpine AS builder
RUN corepack enable && corepack prepare pnpm@latest --activate
WORKDIR /app

# Copy dependencies from deps stage
COPY --from=deps /app/node_modules ./node_modules

# Copy source code
COPY . .

# Build arguments for environment variables (optional defaults)
ARG SUPERVISOR_HOST=localhost
ARG SUPERVISOR_PORT=9001
ARG SUPERVISOR_USERNAME=
ARG SUPERVISOR_PASSWORD=

# Set environment variables for production build
ENV NEXT_TELEMETRY_DISABLED=1
ENV NODE_ENV=production
ENV SUPERVISOR_HOST=${SUPERVISOR_HOST}
ENV SUPERVISOR_PORT=${SUPERVISOR_PORT}
ENV SUPERVISOR_USERNAME=${SUPERVISOR_USERNAME}
ENV SUPERVISOR_PASSWORD=${SUPERVISOR_PASSWORD}

# Build the Next.js application
RUN pnpm build

# Stage 3: Production runner
FROM node:20-alpine AS runner
WORKDIR /app

ENV NODE_ENV=production
ENV NEXT_TELEMETRY_DISABLED=1

# Create non-root user
RUN addgroup --system --gid 1001 nodejs && \
    adduser --system --uid 1001 nextjs

# Copy necessary files from builder
# Note: public directory is optional - only copy if it exists
COPY --from=builder /app/.next/standalone ./
COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static

# Switch to non-root user
USER nextjs

# Expose port
EXPOSE 3000

ENV PORT=3000
ENV HOSTNAME="0.0.0.0"

# Runtime environment variables (can be overridden at runtime)
ENV SUPERVISOR_HOST=localhost
ENV SUPERVISOR_PORT=9001
ENV SUPERVISOR_USERNAME=
ENV SUPERVISOR_PASSWORD=

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

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