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 \
    bind-tools \
    git \
    curl

WORKDIR /build

# Copy shared source files from parent directory first
COPY src/*.cr src/
COPY src/types/ src/types/

# Copy service-specific files
COPY src/dns-manager/ src/dns-manager/

# Install dependencies
WORKDIR /build/src/dns-manager
RUN shards install

# Build the binary
RUN crystal build --release --static src/main.cr -o dns-manager

# Runtime stage
FROM alpine:3.19

RUN apk add --no-cache \
    ca-certificates \
    tzdata \
    openssl \
    yaml \
    bind-tools \
    bind-libs

WORKDIR /app

# Copy the binary from builder
COPY --from=builder /build/src/dns-manager/dns-manager .

# Create non-root user and set permissions
RUN adduser -D appuser && \
    chown -R appuser:appuser /app && \
    chmod 550 /app/dns-manager

USER appuser

ENV PORT=8081
ENV KEMAL_ENV=production

EXPOSE 8081

ENTRYPOINT ["/app/dns-manager"]
