# Multi-stage build for Gallus CMS Backend

# Stage 1: Builder
FROM node:20-alpine AS builder

WORKDIR /app

RUN apk add --no-cache python3 make g++ vips-dev

COPY package*.json ./
RUN npm ci || npm install

COPY . .

RUN npm run db:generate || true

RUN npm run build


# Stage 2: Production
FROM node:20-alpine

WORKDIR /app

RUN apk add --no-cache git sqlite vips vips-dev python3 make g++

COPY --from=builder /app/package*.json ./

RUN npm ci --omit=dev || npm install --production && \
    npm rebuild sharp

RUN apk del python3 make g++ vips-dev


# Copy built files
COPY --from=builder /app/dist ./dist
COPY --from=builder /app/src/db/migrations ./dist/db/migrations

COPY --from=builder /app/migrate-production.js ./migrate-production.js
COPY --from=builder /app/data/images ./data/images

RUN mkdir -p /app/workspace /app/data

RUN chown -R node:node /app
USER node

EXPOSE 8080

ENV NODE_ENV=production
ENV PORT=8080
ENV DATABASE_PATH=/app/data/gallus_cms.db


CMD ["/bin/sh", "-lc", "\
mkdir -p /app/data/images/events /app/data/images/gallery; \
echo 'Running Drizzle migrations...'; \
npx drizzle-kit generate:sqlite || true; \
npx drizzle-kit migrate || true; \
node dist/index.js \
"]
