# ---- Build CSS in a throwaway stage (keeps Tailwind out of the runtime image) ----
FROM node:20-alpine AS assets
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npx tailwindcss -i ./src/public/css/input.css -o ./src/public/css/app.css --minify

# ---- Runtime image ----
FROM node:20-alpine
WORKDIR /app

# Baileys needs no Chromium, but it does use native crypto — alpine is fine.
ENV NODE_ENV=production

COPY package*.json ./
RUN npm ci --omit=dev && npm cache clean --force

# Bring in the source + the pre-built CSS from the assets stage
COPY . .
COPY --from=assets /app/src/public/css/app.css ./src/public/css/app.css

# Persisted data lives on a mounted volume (see docker-compose.yml)
RUN mkdir -p storage/sessions storage/uploads && \
    addgroup -S app && adduser -S app -G app && \
    chown -R app:app /app
USER app

EXPOSE 3000

# Run migrations then start. (Use an entrypoint script so the DB is ready first.)
CMD ["sh", "-c", "node src/scripts/migrate.js && node server.js"]
