# Build stage
FROM node:20-alpine AS builder

WORKDIR /app

COPY package*.json ./
RUN npm ci

COPY tsconfig.json ./
COPY src ./src

RUN npm run build

# Production stage
FROM node:20-alpine

WORKDIR /app

ENV NODE_ENV=production
ENV PORT=4000

COPY package*.json ./
RUN npm ci --omit=dev

COPY --from=builder /app/dist ./dist
# schema.sql is not compiled; needed at runtime for migrations
COPY --from=builder /app/src/db/schema.sql ./dist/db/

EXPOSE 4000

# Run migrations then start the server (migrate may fail if DB not ready; index.js will retry on first request)
CMD ["sh", "-c", "node dist/db/migrate.js 2>/dev/null || true && node dist/index.js"]
