FROM crystallang/crystal:1.14.0-alpine AS builder

# Install build dependencies
RUN apk add --no-cache \
    yaml-dev \
    openssl-dev \
    zlib-dev \
    sqlite-dev \
    postgresql-dev \
    git \
    curl

# Set build arguments
ARG APP_NAME=metrics-service

WORKDIR /app

# Copy source files
COPY src/*.cr src/
COPY src/metrics-service/ src/metrics-service/

# Copy and install dependencies
COPY src/metrics-service/shard.yml ./
RUN shards install

# Build the binary
RUN crystal build --release --static src/metrics-service/src/main.cr -o "${APP_NAME}"

# Runtime stage
FROM alpine:3.19

# Install runtime dependencies
RUN apk add --no-cache \
    ca-certificates \
    tzdata \
    openssl \
    yaml

WORKDIR /app

# Copy the binary from builder
COPY --from=builder /app/"${APP_NAME}" .

# Create data directory for metrics and set permissions
RUN mkdir -p /data && \
    adduser -D appuser && \
    chown -R appuser:appuser /app /data && \
    find /app -type f -exec chmod 500 {} \; && \
    find /app -type d -exec chmod 755 {} \; && \
    chmod 755 /app/"${APP_NAME}" && \
    chmod 700 /data

USER appuser

# Set environment variables
ENV PORT=8080
ENV KEMAL_ENV=production

# Volume for metrics data
VOLUME ["/data"]

# Expose port
EXPOSE 8080

ENTRYPOINT ["/app/${APP_NAME}"]
