# =============================================================================
# GoHorse Jobs Backend - Optimized Production Dockerfile
# =============================================================================

# -----------------------------------------------------------------------------
# Stage 1: Build
# -----------------------------------------------------------------------------
FROM golang:1.24-alpine AS builder

WORKDIR /build

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

# Cache dependencies
COPY go.mod go.sum ./
RUN go mod download && go mod verify

# Copy source code
COPY . .

# Build with optimizations:
# - CGO_ENABLED=0: Static binary (no C dependencies)
# - ldflags -s -w: Strip debug info for smaller binary
# - trimpath: Remove local paths from binary
RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build \
    -ldflags="-s -w -X main.Version=$(git describe --tags --always --dirty 2>/dev/null || echo 'dev')" \
    -trimpath \
    -o /app/main ./cmd/api

# -----------------------------------------------------------------------------
# Stage 2: Production (Minimal Image)
# -----------------------------------------------------------------------------
FROM alpine:3.19

# Security: Run as non-root user
RUN addgroup -g 1001 -S appgroup && \
    adduser -u 1001 -S appuser -G appgroup

WORKDIR /app

# Copy timezone data and CA certificates from builder
COPY --from=builder /usr/share/zoneinfo /usr/share/zoneinfo
COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/

# Copy binary and migrations
COPY --from=builder /app/main .
COPY --from=builder /build/migrations ./migrations

# Set ownership to non-root user
RUN chown -R appuser:appgroup /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 -qO- http://localhost:8080/health || exit 1

# Environment defaults
ENV PORT=8080 \
    TZ=America/Sao_Paulo

CMD ["./main"]
