# 1. Node.js Build-Stage
FROM forgejo.edf-bootstrap.cx.fg1.ffm.osc.live/devfw-cicd/node:20.18.1 AS build

WORKDIR /app

COPY package*.json ./
COPY tsconfig.json ./
COPY tsconfig.backend.json ./
COPY . .

RUN npm install cors
RUN npm install -g npm@11.2.0
RUN npm install

RUN npx tsc -p tsconfig.backend.json
RUN npx tsc -p tsconfig.frontend.json

# 2. Rust build-Stage
FROM forgejo.edf-bootstrap.cx.fg1.ffm.osc.live/devfw-cicd/rust:1.74.0 AS rust-build
RUN cargo install iching

# 3. Final runtime
FROM forgejo.edf-bootstrap.cx.fg1.ffm.osc.live/devfw-cicd/node:20.18.1

WORKDIR /app

# Copy node_modules and all generated data 
COPY --from=build /app/node_modules ./node_modules
COPY --from=build /app/dist ./dist
COPY --from=build /app/frontend/index.html ./dist/frontend/
COPY --from=build /app/package.json ./dist/backend/

# Copy iching library
COPY --from=rust-build /usr/local/cargo/bin/iching /usr/local/bin/iching

# Frontend: rename from .js to .mjs
RUN find dist/frontend -name "*.js" -exec bash -c 'mv "$0" "${0%.js}.mjs"' {} \;

COPY start.sh ./start.sh
RUN chmod +x ./start.sh

CMD ["./start.sh"]