##### Builder stage ###########################################################
FROM node:18-slim AS builder
WORKDIR /app

# Install dependencies (dev + prod) so we can build TypeScript
COPY package.json yarn.lock ormconfig.json ./
RUN yarn install --frozen-lockfile

# Build TypeScript -> dist
COPY . .
RUN yarn build

# Prune to production dependencies only (keeps sqlite3 from dependencies)
RUN yarn install --frozen-lockfile --production

##### Runtime stage ###########################################################
FROM node:18-slim
WORKDIR /app

ENV NODE_ENV=production
ENV PORT=3101

# Copy compiled app and production node_modules from builder
COPY --from=builder /app/dist ./dist
COPY --from=builder /app/node_modules ./node_modules
COPY --from=builder /app/ormconfig.json ./

RUN mkdir -p /app/uploads /app/database

# Include the sqlite database that migrations already prepared
COPY --from=builder /app/src/database/database.sqlite ./database/

EXPOSE 3101
CMD ["node", "dist/server.js"]