# syntax=docker/dockerfile:1.7

# Use Alpine base image for smaller size
FROM node:lts-alpine AS builder
ENV PNPM_HOME=/pnpm
ENV PATH="$PNPM_HOME:$PATH"
RUN corepack enable && corepack prepare pnpm@10.19.0 --activate

WORKDIR /workspace

COPY package.json pnpm-workspace.yaml pnpm-lock.yaml ./
COPY be/apps/core/package.json be/apps/core/package.json
COPY be/apps/dashboard/package.json be/apps/dashboard/package.json
COPY apps/web/package.json apps/web/package.json
COPY patches/ ./patches/

RUN pnpm fetch --filter core...
RUN pnpm fetch --filter '@afilmory/web...'
RUN pnpm fetch --filter '@afilmory/dashboard...'

COPY . .

RUN pnpm install --filter core... --filter '@afilmory/web...' --filter '@afilmory/dashboard...' --frozen-lockfile
RUN pnpm --filter @afilmory/web build:serve & \
    pnpm --filter @afilmory/dashboard build & \
    pnpm --filter core build & \
    wait
RUN mkdir -p be/apps/core/dist/static/web && cp -r apps/web/dist/* be/apps/core/dist/static/web/
RUN mkdir -p be/apps/core/dist/static/dashboard && cp -r be/apps/dashboard/dist/* be/apps/core/dist/static/dashboard/

FROM node:lts-alpine AS runner
ENV NODE_ENV=production
WORKDIR /app

# Runtime deps for image processing:
# - perl: required by exiftool-vendored on Linux
# - perl-image-exiftool: provides the exiftool binary
# - vips: runtime library for sharp
# - libheif: enable HEIF/HEIC support in libvips when available
RUN apk add --no-cache \
  curl \
  perl \
  exiftool \
  perl-image-exiftool \
  vips \
  libheif \
  libc6-compat \
  gcompat \
  && EXIFTOOL_BIN="$(command -v exiftool)" \
  && echo "Using exiftool binary at ${EXIFTOOL_BIN}" \
  && "${EXIFTOOL_BIN}" -ver \
  && ln -sf "${EXIFTOOL_BIN}" /usr/local/bin/exiftool
ENV EXIFTOOL_PATH=/usr/local/bin/exiftool
COPY --from=builder /workspace/be/apps/core/dist ./dist
COPY --from=builder /workspace/be/packages/db/migrations ./migrations
COPY --from=builder /workspace/be/apps/core/docker-entrypoint.sh ./docker-entrypoint.sh
COPY --from=builder /workspace/patches/ ./patches/


RUN chmod +x ./docker-entrypoint.sh

RUN if [ -f dist/package.json ]; then \
  cd dist && \
  npm install --omit=dev --no-audit --no-fund; \
  fi

EXPOSE 1841

ENTRYPOINT ["./docker-entrypoint.sh"]
CMD ["node", "./dist/main.js"]
