# AWOOOI Web - Production Dockerfile
# syntax=docker/dockerfile:1
# 首席架構師 Review C1 (2026-04-05 Claude Code): BuildKit inline cache 需要 ARG 宣告
ARG BUILDKIT_INLINE_CACHE=1

FROM node:20-alpine AS base

# Install pnpm
RUN corepack enable && corepack prepare pnpm@9.0.0 --activate

FROM base AS deps
WORKDIR /app

# Copy package files
COPY package.json pnpm-lock.yaml pnpm-workspace.yaml ./
COPY apps/web/package.json ./apps/web/
COPY packages/tsconfig/package.json ./packages/tsconfig/
COPY packages/eslint-config/package.json ./packages/eslint-config/
COPY packages/lewooogo-core/package.json ./packages/lewooogo-core/

# Install dependencies
RUN pnpm install --frozen-lockfile

FROM base AS builder
WORKDIR /app

# Copy deps
COPY --from=deps /app/node_modules ./node_modules
COPY --from=deps /app/apps/web/node_modules ./apps/web/node_modules
COPY --from=deps /app/packages ./packages

# 2026-04-01 ogt: CACHE_BUST 強制讓 source 層失效（每次 commit 不同）
# deps 層 (pnpm install) 仍可 cache；只有 COPY . . 以下強制重建
# 解決原本 --no-cache 連 deps 也清掉的問題
ARG CACHE_BUST=dev
RUN echo "$CACHE_BUST" > /dev/null

# Copy source
COPY . .

# Build-time environment variables (NEXT_PUBLIC_* 會被打包進 JS)
ARG NEXT_PUBLIC_API_URL=http://localhost:8000
ARG NEXT_PUBLIC_SENTRY_DSN=
ENV NEXT_PUBLIC_API_URL=${NEXT_PUBLIC_API_URL}
ENV NEXT_PUBLIC_SENTRY_DSN=${NEXT_PUBLIC_SENTRY_DSN}
ENV NEXT_TELEMETRY_DISABLED=1

# 2026-04-06 ogt: --mount=type=cache 持久化 .next/cache，跨 build 增量編譯
# 只有變更的頁面重新編譯，未變更頁面直接用 cache → 節省 3-4 min
# 2026-04-12 Claude Code: 補 turbo cache mount，Turborepo task hash 跨 build 生效
# /root/.cache/turbo 存放 turbo 的 task 輸出快取，避免每次重跑未變動的 packages
RUN --mount=type=cache,target=/app/apps/web/.next/cache \
    --mount=type=cache,target=/root/.cache/turbo \
    pnpm turbo build --filter=@awoooi/web

FROM base AS runner
WORKDIR /app

ENV NODE_ENV production
ENV NEXT_TELEMETRY_DISABLED 1

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

# Copy built files
COPY --from=builder /app/apps/web/public ./apps/web/public
COPY --from=builder --chown=nextjs:nodejs /app/apps/web/.next/standalone ./
COPY --from=builder --chown=nextjs:nodejs /app/apps/web/.next/static ./apps/web/.next/static

USER nextjs

EXPOSE 3000

ENV PORT 3000
ENV HOSTNAME "0.0.0.0"

CMD ["node", "apps/web/server.js"]
