# Build stage
FROM oven/bun:1-alpine as builder

WORKDIR /app

# Copy workspace files
COPY package.json bun.lockb ./
COPY apps/wcag-ada/dashboard/package.json ./apps/wcag-ada/dashboard/
COPY apps/wcag-ada/shared/package.json ./apps/wcag-ada/shared/

# Install dependencies
RUN bun install --frozen-lockfile

# Copy source code
COPY apps/wcag-ada/dashboard ./apps/wcag-ada/dashboard
COPY apps/wcag-ada/shared ./apps/wcag-ada/shared
COPY tsconfig.json ./

# Build the application
WORKDIR /app/apps/wcag-ada/dashboard
RUN bun run build

# Production stage with nginx
FROM nginx:alpine

# Install runtime dependencies
RUN apk add --no-cache curl

# Copy nginx configuration
COPY apps/wcag-ada/dashboard/nginx.conf /etc/nginx/nginx.conf

# Copy built application
COPY --from=builder /app/apps/wcag-ada/dashboard/dist /usr/share/nginx/html

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

# Set ownership
RUN chown -R nodejs:nodejs /usr/share/nginx/html && \
    chown -R nodejs:nodejs /var/cache/nginx && \
    chown -R nodejs:nodejs /var/log/nginx && \
    chown -R nodejs:nodejs /etc/nginx/conf.d && \
    touch /var/run/nginx.pid && \
    chown -R nodejs:nodejs /var/run/nginx.pid

USER nodejs

# Expose port
EXPOSE 8080

# Health check
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
  CMD curl -f http://localhost:8080/ || exit 1

# Start nginx
CMD ["nginx", "-g", "daemon off;"]