# Build stage - using pnpm for workspace dependency resolution
FROM node:20-alpine AS deps

# Install pnpm
RUN npm install -g pnpm

WORKDIR /workspace

# Copy workspace configuration files
COPY pnpm-workspace.yaml package.json pnpm-lock.yaml* ./

# Copy shared packages (required for workspace:* dependencies)
COPY packages/ ./packages/

# Copy the app component
COPY apps/{{COMPONENT_NAME}}/ ./apps/{{COMPONENT_NAME}}/

# Install dependencies using pnpm (resolves workspace:* correctly)
RUN pnpm install --frozen-lockfile || pnpm install

# Build stage
FROM node:20-alpine AS builder

RUN npm install -g pnpm

WORKDIR /workspace

COPY --from=deps /workspace ./

# Build the Next.js app
WORKDIR /workspace/apps/{{COMPONENT_NAME}}
RUN pnpm build

# Production stage
FROM node:20-alpine AS runner

WORKDIR /app

ENV NODE_ENV=production
ENV NEXT_TELEMETRY_DISABLED=1

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

# Copy built standalone output
COPY --from=builder /workspace/apps/{{COMPONENT_NAME}}/.next/standalone ./
COPY --from=builder /workspace/apps/{{COMPONENT_NAME}}/.next/static ./apps/{{COMPONENT_NAME}}/.next/static
COPY --from=builder /workspace/apps/{{COMPONENT_NAME}}/public ./apps/{{COMPONENT_NAME}}/public

USER nextjs

EXPOSE {{PORT}}

ENV PORT={{PORT}}
ENV HOSTNAME="0.0.0.0"

# Start the Next.js server
CMD ["node", "apps/{{COMPONENT_NAME}}/server.js"]
