# Multi-stage build for efficient image size
FROM docker.io/library/golang:1.23-alpine AS builder

# Install build dependencies
RUN apk add --no-cache git ca-certificates wget

# Create non-root user for building
RUN addgroup -S appgroup && adduser -S appuser -G appgroup

# Set working directory
WORKDIR /app

# Copy go mod files first for better layer caching
COPY go.mod go.sum ./

# Download dependencies
RUN go mod download

# Copy source code
COPY . .

# Build the application
RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build \
    -ldflags='-w -s -extldflags "-static"' \
    -a -installsuffix cgo \
    -o api-key-service \
    ./cmd/server

# Final stage - minimal image
FROM docker.io/library/alpine:3.18

# Install runtime dependencies
RUN apk --no-cache add ca-certificates wget tzdata

# Create non-root user
RUN addgroup -S appgroup && adduser -S appuser -G appgroup

# Create directory for the application
WORKDIR /app

# Copy binary from builder stage
COPY --from=builder /app/api-key-service /app/api-key-service

# Copy migration files
COPY --from=builder /app/migrations /app/migrations

# Copy template files
COPY --from=builder /app/templates /app/templates

# Change ownership to non-root user
RUN chown -R appuser:appgroup /app && \
    chmod -R 755 /app/migrations && \
    chmod -R 755 /app/templates

# Switch to non-root user
USER appuser

# Expose ports
EXPOSE 8080 9090

# Health check
HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \
    CMD wget --quiet --tries=1 --spider http://localhost:8080/health || exit 1

# Run the application
CMD ["/app/api-key-service"]
