# Stage 1: Build the frontend
FROM node:22-alpine AS frontend-builder
WORKDIR /app/frontend
COPY frontend/package*.json ./
RUN npm ci --legacy-peer-deps
COPY frontend/ ./
RUN npm run build

# Stage 2: Build the backend
FROM node:22-alpine AS backend-builder
WORKDIR /app/backend
COPY backend/package*.json ./
RUN npm ci
COPY backend/ ./
RUN npm run build

# Stage 3: Production
FROM node:22-alpine AS production
# Install build tools for native modules like better-sqlite3
RUN apk add --no-cache python3 make g++ 
WORKDIR /app

# Copy frontend build
COPY --from=frontend-builder /app/frontend/dist ./frontend/dist

# Copy backend build
WORKDIR /app/backend
COPY --from=backend-builder /app/backend/dist ./dist
COPY --from=backend-builder /app/backend/package*.json ./

# Install production dependencies only (this rebuilds better-sqlite3 for Alpine)
RUN npm ci --omit=dev

# Ensure database directory exists
RUN mkdir -p /app/backend/db && chown -R node:node /app/backend

# Switch to non-root user
USER node

# Expose API and frontend port
EXPOSE 3001

# Start the application
CMD ["node", "dist/index.js"]
