FROM node:22-alpine AS base
WORKDIR /app

ENV NEXT_TELEMETRY_DISABLED=1
ENV PNPM_HOME=/pnpm
ENV PNPM_STORE_PATH=/pnpm/store
ENV PATH=$PNPM_HOME:$PATH

RUN apk add --no-cache libc6-compat \
  && corepack enable \
  && corepack prepare pnpm@10.30.3 --activate \
  && pnpm config set store-dir "$PNPM_STORE_PATH"

FROM base AS deps
COPY package.json pnpm-lock.yaml pnpm-workspace.yaml ./
RUN --mount=type=cache,id=cozsweet-pnpm-store,target=/pnpm/store,sharing=locked \
  pnpm install --frozen-lockfile --prefer-offline

FROM base AS prod-deps
COPY package.json pnpm-lock.yaml pnpm-workspace.yaml ./
RUN --mount=type=cache,id=cozsweet-pnpm-store,target=/pnpm/store,sharing=locked \
  pnpm install --prod --frozen-lockfile --prefer-offline

FROM base AS builder
ARG NEXT_ENV_FILE=.env.local
ENV CI=true
ENV SENTRY_UPLOAD_SOURCEMAPS=0

COPY --from=deps /app/node_modules ./node_modules
COPY . .

RUN --mount=type=secret,id=next_env,target=/tmp/next_env,required=false \
  --mount=type=cache,id=cozsweet-next-cache,target=/app/.next/cache,sharing=locked \
  if [ -f /tmp/next_env ]; then cp /tmp/next_env "$NEXT_ENV_FILE"; fi; \
  pnpm run build; \
  rm -f .env .env.local .env.development .env.production

FROM node:22-alpine AS runner
WORKDIR /app

ENV NODE_ENV=production
ENV NEXT_TELEMETRY_DISABLED=1
ENV HOSTNAME=0.0.0.0
ENV PORT=3000

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

COPY --from=builder /app/public ./public
COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./
COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static
COPY --from=prod-deps --chown=nextjs:nodejs /app/node_modules ./node_modules
COPY --from=builder --chown=nextjs:nodejs /app/src/app/sw.ts ./src/app/sw.ts

USER nextjs
EXPOSE 3000

CMD ["node", "server.js"]
