# 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

# Migrate on boot (retry briefly if Postgres is still starting). Do not hide migrate stderr.
CMD ["sh", "-c", "i=0; until node dist/db/migrate.js; do i=$((i+1)); if [ \"$i\" -ge 5 ]; then echo 'Migration failed after retries — starting API anyway'; break; fi; echo \"Migration attempt $i failed, retrying in 3s...\"; sleep 3; done; node dist/index.js"]
