# --- deps ---
FROM node:20-alpine AS deps
RUN apk add --no-cache libc6-compat openssl
WORKDIR /app
COPY package.json package-lock.json* ./
RUN npm ci

# --- builder ---
FROM node:20-alpine AS builder
RUN apk add --no-cache libc6-compat openssl
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .
RUN npx prisma generate
RUN npm run build

# --- runner ---
FROM node:20-alpine AS runner
RUN apk add --no-cache libc6-compat openssl
WORKDIR /app
ENV NODE_ENV=production
ENV PORT=3000

# Standalone output bundles only what's needed to run.
COPY --from=builder /app/public ./public
COPY --from=builder /app/.next/standalone ./
COPY --from=builder /app/.next/static ./.next/static

# Prisma needs the schema + migrations + CLI + engines to run migrate deploy at
# startup. We copy the FULL packages (not the .bin symlink) so the CLI's bundled
# .wasm files resolve relative to node_modules/prisma/build/, and the entrypoint
# invokes the real entry path directly (see docker-entrypoint.sh).
#   - prisma/            : schema.prisma + migrations/
#   - node_modules/prisma: CLI + prisma_schema_build_bg.wasm and friends
#   - node_modules/@prisma: engines (schema-engine for migrate) + client runtime
#   - node_modules/.prisma: generated client + linux-musl query engine
COPY --from=builder /app/prisma ./prisma
COPY --from=builder /app/node_modules/prisma ./node_modules/prisma
COPY --from=builder /app/node_modules/@prisma ./node_modules/@prisma
COPY --from=builder /app/node_modules/.prisma ./node_modules/.prisma

COPY docker-entrypoint.sh ./docker-entrypoint.sh
RUN chmod +x docker-entrypoint.sh

EXPOSE 3000
VOLUME ["/data"]
CMD ["./docker-entrypoint.sh"]
