# syntax=docker/dockerfile:1

# Use official Node.js image as base
# Next.js 16 requires Node 18.17+ or Node 20+
# Using node:20-alpine for better compatibility with Next.js 16 and Turbopack
FROM node:20-alpine AS builder
WORKDIR /app

# Install git early for commit hash
RUN apk add --no-cache git

# Install pnpm properly for Docker
RUN corepack enable && corepack prepare pnpm@latest --activate

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

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

# Copy source code after dependencies are installed (for better caching)
COPY . .

# Get commit hash (fallback to "unknown" if not in git repo)
# This is done after copying source to avoid cache invalidation
# Test build

ENV NEXT_PUBLIC_API_URL=/api
ENV SERVER_API_URL=https://internal-api.inboxi.ng/api
ENV API_BASE_URL=https://internal-api.inboxi.ng
ENV API_HOSTNAME=internal-api.inboxi.ng

# Ensure .next directory exists and has proper permissions
RUN mkdir -p /app/.next && chmod -R 755 /app/.next

# Build the Next.js application with reduced memory for Turbopack
# Next.js 16 uses Turbopack by default which may need more memory
RUN echo "invalidate cache" && echo $(git rev-parse --short HEAD 2>/dev/null || echo "unknown") > /app/git_commit_sha && \
    NODE_OPTIONS='--max_old_space_size=2048' NEXT_TELEMETRY_DISABLED=1 pnpm run build

# ---- Production Stage ----
# Use a smaller base image for production
FROM node:20-alpine AS runner

# Set working directory inside the container
WORKDIR /app

# Copy the standalone build from builder
COPY --from=builder /app/.next/standalone ./

# Copy static files
COPY --from=builder /app/.next/static ./.next/static

# Copy public files
COPY --from=builder /app/public ./public

# Copy commit hash file from builder
COPY --from=builder /app/git_commit_sha /app/git_commit_sha

EXPOSE 3000

ENV NODE_ENV=production
ENV NEXT_PUBLIC_API_URL=/api
ENV SERVER_API_URL=https://internal-api.inboxi.ng/api
ENV API_BASE_URL=https://internal-api.inboxi.ng
ENV API_HOSTNAME=internal-api.inboxi.ng

# Note: GIT_COMMIT_SHA will be read at runtime, not set as ENV
# The file is available at /app/git_commit_sha if needed

# Start Next.js server
CMD ["node", "server.js"]