# Builder stage
FROM node:lts-bookworm AS oid4vc-fame-builder
SHELL ["/bin/bash", "-c"]

# Install system dependencies for sqlite3
RUN apt-get update && apt-get install -y \
    build-essential \
    python3 \
    libsqlite3-dev \
    && rm -rf /var/lib/apt/lists/*

RUN npm -g install pnpm && SHELL=bash pnpm setup && source /root/.bashrc && pnpm self-update

RUN pnpm add typescript tslib
WORKDIR /opt/fame-aai-identity

COPY /. .
RUN rm -rf /root/.local/share/pnpm/store
RUN rm -rf node_modules package-lock.json pnpm-lock.yaml

# Explicitly install sqlite3 with node-gyp rebuild
RUN pnpm install -r
RUN pnpm add sqlite3
RUN npm install -g node-gyp
RUN npm rebuild sqlite3

# Final stage
FROM node:lts-bookworm
ARG PACKAGE_PATH
ARG NODE_SCRIPT
ENV NODE_SCRIPT="start:dev"

# Install system dependencies for sqlite3 in final stage
RUN apt-get update && apt-get install -y \
    build-essential \
    python3 \
    libsqlite3-dev \
    && rm -rf /var/lib/apt/lists/*

# Install node-gyp globally
RUN npm install -g node-gyp

COPY --from=oid4vc-fame-builder /opt/fame-aai-identity/packages/agent /opt/fame-aai-identity/packages/agent
# package node_modules has symlinks to root node_modules
COPY --from=oid4vc-fame-builder /opt/fame-aai-identity/node_modules /opt/fame-aai-identity/node_modules

WORKDIR /opt/fame-aai-identity/packages/agent

# Rebuild sqlite3 in the final stage
RUN npm rebuild sqlite3

# Expose port 80
EXPOSE 8022
ENTRYPOINT npm run-script ${NODE_SCRIPT}