FROM node:25-alpine AS base
RUN apk add --no-cache libc6-compat
WORKDIR /app

# Builder stage
FROM base AS builder
RUN corepack enable pnpm
# Copy workspace configuration
COPY pnpm-workspace.yaml package.json pnpm-lock.yaml ./
# Create directory structure and copy all package.json files
RUN mkdir -p packages apps services
COPY packages/auth-sdk/package.json ./packages/auth-sdk/
COPY packages/http-client/package.json ./packages/http-client/
COPY packages/logger/package.json ./packages/logger/
COPY packages/tracing/package.json ./packages/tracing/
COPY packages/types/package.json ./packages/types/
COPY packages/config/eslint-config/package.json ./packages/config/eslint-config/
COPY packages/config/prettier-config/package.json ./packages/config/prettier-config/
COPY packages/config/tsconfig/package.json ./packages/config/tsconfig/
COPY apps/web-client/package.json ./apps/web-client/
COPY apps/web-admin/package.json ./apps/web-admin/
COPY services/iam-service/package.json ./services/iam-service/
# Install all dependencies for entire monorepo
RUN --mount=type=cache,id=pnpm,target=/root/.local/share/pnpm/store \
    pnpm install --frozen-lockfile
# Copy all source code
COPY packages ./packages
COPY apps/web-client ./apps/web-client
COPY turbo.json ./
# Build using turbo from root (handles dependency order automatically)
RUN pnpm turbo build --filter=web-client

# Production stage
FROM base AS runner
ENV NODE_ENV=production
RUN addgroup --system --gid 1001 nodejs
RUN adduser --system --uid 1001 nextjs

# Copy the entire workspace to preserve pnpm structure
COPY --from=builder --chown=nextjs:nodejs /app /app

WORKDIR /app/apps/web-client

USER nextjs

EXPOSE 3000
ENV PORT=3000
ENV HOSTNAME="0.0.0.0"

CMD ["node", ".next/standalone/apps/web-client/server.js"]
