# Build stage
FROM node:20-alpine AS builder

WORKDIR /app

# Install build tools for native modules
RUN apk add --no-cache python3 make g++ libusb-dev eudev-dev linux-headers

# Copy root package files for workspace install
COPY package*.json ./
COPY frontend/package*.json ./frontend/

# Install dependencies
RUN --mount=type=cache,target=/root/.npm npm install --legacy-peer-deps

# Copy frontend source
COPY frontend/ ./frontend/

# Build args for Next.js
ARG NEXT_PUBLIC_API_URL
ARG NEXT_PUBLIC_SOLANA_NETWORK
ARG NEXT_PUBLIC_SOLANA_RPC_URL

# Build Next.js app
WORKDIR /app/frontend
ENV NEXT_TELEMETRY_DISABLED=1
ENV NODE_OPTIONS="--max-old-space-size=4096"

# Build with standalone output
RUN --mount=type=cache,target=/app/frontend/.next/cache npx next build

# Production stage
FROM node:20-alpine

WORKDIR /app

# Copy standalone output
COPY --from=builder /app/frontend/.next/standalone ./
COPY --from=builder /app/frontend/.next/static ./frontend/.next/static
COPY --from=builder /app/frontend/public ./frontend/public

# Expose port
EXPOSE 3000

ENV PORT=3000
ENV HOSTNAME="0.0.0.0"

# Start application
CMD ["node", "frontend/server.js"]
