FROM oven/bun:slim AS base
WORKDIR /app

FROM base AS install
COPY package.json bun.lock ./
RUN bun install --frozen-lockfile

FROM base AS build
ENV NODE_ENV=production
COPY --from=install /app/node_modules node_modules
COPY . .
RUN bun run build

FROM base AS release
ARG VERSION=dev
ARG REVISION=unknown
ARG CREATED
LABEL org.opencontainers.image.title="nadir" \
      org.opencontainers.image.description="SvelteKit dashboard for nadir-agent — central web console for Nadir backend nodes." \
      org.opencontainers.image.documentation="https://nadir.urania.dev/docs" \
      org.opencontainers.image.url="https://tea.urania.dev/urania/nadir-webui" \
      org.opencontainers.image.source="https://tea.urania.dev/urania/nadir-webui" \
      org.opencontainers.image.authors="Mirko Isaia <m.isaia@urania.dev>" \
      org.opencontainers.image.licenses="MIT" \
      org.opencontainers.image.version="${VERSION}" \
      org.opencontainers.image.revision="${REVISION}" \
      org.opencontainers.image.created="${CREATED}"
ENV NODE_ENV=production \
    DATABASE_URL=/app/data/db.sqlite \
    HOST=0.0.0.0 \
    PORT=3000 \
    ORIGIN=http://localhost:3000 \
    REPOSITORY_URL=https://tea.urania.dev/api/v1/repos/urania/nadir-agent/releases/latest
# full node_modules: drizzle-kit (devDep) is needed for `drizzle-kit migrate` at startup
WORKDIR /app
COPY --from=install /app/node_modules node_modules
COPY --from=build /app/build build
COPY --from=build /app/config config
COPY drizzle drizzle
COPY drizzle.config.ts package.json ./
RUN mkdir -p /app/data 
COPY drizzle.config.ts package.json ./
RUN bun run db:migrate 
VOLUME /app/data
EXPOSE 3000
# apply migrations (creates db.sqlite if absent), then start the server
CMD ["sh", "-c", "bun run db:migrate && bun /app/build/index.js"]
