FROM node:24.18.1-alpine AS builder
WORKDIR /app

RUN npm install -g pnpm@11.18.0

# 1. Alle Projektdateien in den Container bringen
COPY . .

# 2. Abhängigkeiten installieren
RUN pnpm install --frozen-lockfile

# Zwingt pnpm, alle nativen Binärdateien für Alpine physisch bereit zustellen
RUN pnpm add -w @rollup/rollup-linux-x64-musl lightningcss-linux-x64-musl @tailwindcss/oxide-linux-x64-musl --save-optional --config.ignore-scripts=false

ENV BASE_PATH=/
ENV PORT=8080

RUN pnpm -r --if-present run build

FROM node:24.18.1-alpine AS runner
WORKDIR /app

RUN npm install -g pnpm@11.18.0

COPY pnpm-lock.yaml pnpm-workspace.yaml package.json ./
COPY lib/db/package.json lib/db/
COPY lib/api-spec/package.json lib/api-spec/
COPY lib/api-zod/package.json lib/api-zod/
COPY lib/api-client-react/package.json lib/api-client-react/
COPY artifacts/api-server/package.json artifacts/api-server/
COPY artifacts/toolrate/package.json artifacts/toolrate/

RUN pnpm install --frozen-lockfile --prod

# HIER ERGÄNZT: drizzle-kit und pg am Ende hinzugefügt, damit das CMD-Skript nicht abstürzt!
RUN pnpm add -w @rollup/rollup-linux-x64-musl lightningcss-linux-x64-musl @tailwindcss/oxide-linux-x64-musl drizzle-kit pg --save-optional --prod

# Kopiert den gesamten Ordner lib/db (inkl. src/), da es kein dist/ gibt
COPY --from=builder /app/lib/db lib/db
COPY --from=builder /app/artifacts/api-server/dist artifacts/api-server/dist
COPY --from=builder /app/artifacts/toolrate/dist artifacts/toolrate/dist

ENV NODE_ENV=production
ENV STATIC_DIR=/app/artifacts/toolrate/dist/public

ARG COMMIT_SHA=""
ARG BUILD_DATE=""
ARG VERSION=""
ENV COMMIT_SHA=${COMMIT_SHA}
ENV BUILD_DATE=${BUILD_DATE}
ENV VERSION=${VERSION}

EXPOSE 8080

CMD ["sh", "-c", "pnpm --filter @workspace/db run push-force && node --enable-source-maps artifacts/api-server/dist/index.mjs"]
