FROM node:lts-alpine AS base

# Install system dependencies needed for canvas and other native modules
RUN apk add --no-cache \
    python3 \
    make \
    g++ \
    cairo-dev \
    jpeg-dev \
    pango-dev \
    musl-dev \
    giflib-dev \
    pixman-dev \
    pangomm-dev \
    libjpeg-turbo-dev \
    freetype-dev

# Install turbo globally
RUN npm install -g turbo

FROM base AS pruner
WORKDIR /app
COPY . .
RUN turbo prune api --docker

# Add lockfile and package.json's of isolated subworkspace
FROM base AS installer
WORKDIR /app

# First install the dependencies (this is done before copying the source code to better leverage Docker layer caching)
COPY .gitignore .gitignore
COPY --from=pruner /app/out/json/ .
COPY --from=pruner /app/out/package-lock.json ./package-lock.json
RUN npm ci

# Build the project
COPY --from=pruner /app/out/full/ .

# Generate Prisma client and schemas before building
RUN npm run db:generate --workspace=@repo/db

RUN turbo run build --filter=api...

FROM base AS runner
WORKDIR /app

# Don't run production as root
RUN addgroup --system --gid 1001 nodejs
RUN adduser --system --uid 1001 hono
USER hono

COPY --from=installer --chown=hono:nodejs /app/apps/api/dist ./dist
COPY --from=installer --chown=hono:nodejs /app/apps/api/package.json ./package.json

# Copy node_modules from installer stage
COPY --from=installer --chown=hono:nodejs /app/node_modules ./node_modules
COPY --from=installer --chown=hono:nodejs /app/apps/api/node_modules ./apps/api/node_modules

# Expose port
EXPOSE 3001

CMD ["npm", "start"]
