# Build stage
FROM golang:1.22-alpine AS builder

RUN apk add --no-cache git ca-certificates

WORKDIR /app

# Copy go mod files
COPY go.mod go.sum* ./
RUN go mod download

# Copy source code
COPY . .

# Build the binary
RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build \
    -ldflags="-w -s" \
    -o /orchard-server \
    ./cmd/orchard-server

# Runtime stage
FROM alpine:3.19

RUN apk add --no-cache ca-certificates tzdata

# Create non-root user
RUN addgroup -g 1000 orchard && \
    adduser -u 1000 -G orchard -s /bin/sh -D orchard

WORKDIR /app

# Copy binary from builder
COPY --from=builder /orchard-server /app/orchard-server

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

# Set ownership
RUN chown -R orchard:orchard /app

USER orchard

EXPOSE 8080

HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
    CMD wget --no-verbose --tries=1 --spider http://localhost:8080/health || exit 1

ENTRYPOINT ["/app/orchard-server"]
