# ***NEVER FORGET THE PRINCIPLES RULES***

# Build stage - Use Node.js to avoid AVX CPU requirement
FROM node:20-alpine AS builder

WORKDIR /app

COPY package.json bun.lock* ./

# Install dependencies using npm (works without AVX)
RUN npm install

COPY . .

# Client: Vite build via Node.js
# API: Skip bun build, copy src files directly (Bun will run them at runtime)
RUN npm run build:client

FROM node:20-alpine AS deps
WORKDIR /app
COPY package.json bun.lock* ./
RUN npm install --production

# Production stage
FROM oven/bun:1.3-alpine AS runner
WORKDIR /app

# Create non-root user
RUN addgroup -g 1001 -S nodejs && \
  adduser -S nodejs -u 1001

# Copy necessary files
COPY --from=deps /app/node_modules ./node_modules
COPY --from=builder /app/src ./src
COPY --from=builder /app/dist/client ./dist/client
COPY --from=builder /app/package.json ./

# Set permissions
RUN chown -R nodejs:nodejs /app

# Switch to non-root user
USER nodejs

# Expose port
EXPOSE 3000

# Health check
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
  CMD bun --eval 'fetch("http://localhost:3000/health").then(r => process.exit(r.ok ? 0 : 1)).catch(() => process.exit(1))'

# Start the application
CMD ["bun", "run", "start"]
