# Stage 1: build Storybook
FROM oven/bun:latest AS builder
WORKDIR /app
COPY package*.json ./
RUN bun install
# Only copy necessary files for building Storybook
COPY .storybook/ ./.storybook/
COPY packages/ ./packages/
COPY tsconfig.json ./
COPY tailwind.config.js ./
COPY postcss.config.mjs ./
COPY public/ ./public/
RUN bun install
RUN bun run build-storybook

# Stage 2: Serve with nginx as non-root user - optimized for size
FROM nginx:1.25.4-alpine-slim

# Install envsubst and clean up package cache in the same layer
RUN apk add --no-cache gettext

# Copy the nginx configuration template
COPY deploy/storybook/nginx.conf /etc/nginx/templates/default.conf.template

# Set environment variables with defaults
ENV GZIP_COMPRESSION_LEVEL=6 \
    HTML_CACHE_CONTROL="public, no-transform, max-age=604800" \
    ASSETS_CACHE_CONTROL="public, no-transform, max-age=604800" \
    MEDIA_CACHE_CONTROL="public, no-transform, max-age=2592000"

# Copy the static files from builder
COPY --from=builder /app/storybook-static /usr/share/nginx/html

# Remove unnecessary files to reduce image size
RUN rm -rf /usr/share/nginx/html/*.map && \
    find /usr/share/nginx/html -type f -name "*.js" | xargs gzip -k && \
    find /usr/share/nginx/html -type f -name "*.css" | xargs gzip -k

# Create a non-root user and group
RUN addgroup -g 1001 -S appgroup && \
    adduser -u 1001 -S appuser -G appgroup && \
    # Set proper permissions
    chown -R appuser:appgroup /usr/share/nginx/html && \
    chown -R appuser:appgroup /var/cache/nginx && \
    chown -R appuser:appgroup /var/log/nginx && \
    chown -R appuser:appgroup /etc/nginx/conf.d && \
    chown -R appuser:appgroup /etc/nginx/templates && \
    touch /var/run/nginx.pid && \
    chown -R appuser:appgroup /var/run/nginx.pid && \
    chmod -R 755 /usr/share/nginx/html

USER appuser

EXPOSE 80

# Use nginx's built-in docker-entrypoint script which handles template substitution
CMD ["nginx", "-g", "daemon off;"]
