# Multi-stage build for Security Center Backend
FROM public.ecr.aws/docker/library/golang:1.24.0-alpine AS builder

# Install build dependencies
RUN apk add --no-cache git make

# Set working directory
WORKDIR /app

# Copy go mod files
COPY go.mod go.sum ./

# Download dependencies
RUN go mod download

# Copy source code
COPY . .
RUN mkdir -p configs && touch configs/config.example.yaml

# Build the application without forcing a full stdlib rebuild on every image build.
RUN CGO_ENABLED=0 GOOS=linux go build -o /app/bin/api ./cmd/api

# Production stage
FROM public.ecr.aws/docker/library/alpine:latest

# Install ca-certificates for HTTPS calls
RUN apk --no-cache add ca-certificates tzdata

# Create non-root user
RUN addgroup -g 1000 appuser && \
    adduser -D -u 1000 -G appuser appuser

WORKDIR /app

# Copy binary from builder
COPY --from=builder /app/bin/api .

# Copy config template
COPY --from=builder /app/configs/config.example.yaml ./configs/config.yaml

# Change ownership
RUN chown -R appuser:appuser /app

# Switch to non-root user
USER appuser

# Expose port
EXPOSE 8080

# Health check
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
  CMD wget -q -O - http://localhost:8080/health > /dev/null 2>&1 || exit 1

# Run the application
CMD ["./api"]
