# Build stage
FROM golang:1.24-alpine AS builder

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

# Set Go proxy (can be overridden with --build-arg GOPROXY=...)
ARG GOPROXY=https://proxy.golang.org,direct
ENV GOPROXY=${GOPROXY}

# Set working directory
WORKDIR /app

# Copy go mod files
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" \
    -o /bin/session-coordinator \
    ./services/session-coordinator/cmd/server

# Final stage
FROM alpine:3.18

# Install ca-certificates and curl for HTTPS and health check
RUN apk --no-cache add ca-certificates curl

# Create non-root user
RUN adduser -D -s /bin/sh mpc

# Copy binary from builder
COPY --from=builder /bin/session-coordinator /bin/session-coordinator

# Switch to non-root user
USER mpc

# Expose ports
EXPOSE 50051 8080

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

# Run the application
ENTRYPOINT ["/bin/session-coordinator"]
