FROM node:lts-alpine AS base

RUN corepack enable
RUN apk add --no-cache libc6-compat git

# --- Dependencies stage ---
FROM base AS deps
WORKDIR /app
COPY package.json pnpm-lock.yaml ./
RUN pnpm install --frozen-lockfile

# --- Builder stage ---
FROM base AS builder
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .

ENV DOCKER_BUILD=true
ENV NEXT_TELEMETRY_DISABLED=1
ENV TINA_PUBLIC_IS_LOCAL=false
ENV NODE_OPTIONS="--dns-result-order=ipv4first"

RUN npx tinacms build && npx next build
RUN npx pagefind --site .next --output-path .next/static/pagefind

# --- Runner stage ---
FROM base AS runner
WORKDIR /app

ENV NODE_ENV=production
ENV NEXT_TELEMETRY_DISABLED=1
ENV TINA_PUBLIC_IS_LOCAL=false

RUN addgroup --system --gid 1001 nodejs
RUN adduser --system --uid 1001 nextjs

# Copy standalone output
COPY --from=builder /app/.next/standalone ./
COPY --from=builder /app/.next/static ./.next/static
COPY --from=builder /app/public ./public
COPY --from=builder /app/content ./content
COPY --from=builder /app/tina ./tina

# Initialize a local git repo for IsomorphicBridge
# IsomorphicBridge requires a .git directory with at least one commit
RUN git init && \
    git config user.email "docs@linumiq.com" && \
    git config user.name "TinaDocs" && \
    git add -A && \
    git commit -m "Initial content"

# Copy the startup indexing script
COPY --from=builder /app/scripts/index-database.mjs ./scripts/index-database.mjs

# Pagefind static search index
COPY --from=builder /app/.next/static/pagefind ./.next/static/pagefind

# Create cache directory with correct permissions
# IsomorphicBridge needs write access to .git and content for commits
RUN mkdir -p .next/cache && \
    chown -R nextjs:nodejs .next/cache .git content tina

USER nextjs

EXPOSE 3000

ENV PORT=3000
ENV HOSTNAME="0.0.0.0"

# Entrypoint: index content into Redis, then start Next.js
CMD ["sh", "-c", "node scripts/index-database.mjs && node server.js"]
