# --- Stage 1: Build ---
FROM node:20-alpine as builder

WORKDIR /app

RUN npm install -g pnpm@9
RUN npm install -g dotenv-cli

COPY package.json pnpm-lock.yaml pnpm-workspace.yaml ./
COPY packages packages
COPY tooling tooling
COPY .env .env
COPY .env.production .env.production
COPY .env.staging .env.staging

# Load env file and echo a specific variable
# RUN dotenv -e .env -- printenv | grep 'SUPABASE' || true
RUN pnpm install --frozen-lockfile

COPY . .

ENV NODE_ENV=production

RUN set -a \
    && . .env \
    && . .env.production \
    && . .env.staging \
    && set +a \
    && node check-env.js \
    && pnpm build


# --- Stage 2: Runtime ---
FROM node:20-alpine
ARG APP_ENV=production

WORKDIR /app

COPY --from=builder /app ./

RUN cp ".env.${APP_ENV}" .env.local

RUN npm install -g pnpm@9 \
    && pnpm install --prod --frozen-lockfile

ENV NODE_ENV=production

# 🔍 Optional: Log key envs for debug
RUN echo "📄 .env contents:" && cat .env.local \
    && echo "🔧 Current ENV available to Next.js build:" && printenv | grep -E 'SUPABASE|STRIPE|NEXT|NODE_ENV' || true


EXPOSE 3000

CMD ["pnpm", "start"]
