# Build Stage
FROM golang:1.23-alpine AS builder

WORKDIR /app

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

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

# Download dependencies
RUN go mod download

# Copy source code
COPY . .

# Build the application
# CGO_ENABLED=0 ensures a static binary
ARG TARGETOS TARGETARCH
RUN CGO_ENABLED=0 GOOS=$TARGETOS GOARCH=$TARGETARCH go build -o api-server ./cmd/api/main.go

# Runtime Stage
FROM alpine:latest

WORKDIR /app

# Install ca-certificates for database connections (TLS)
RUN apk add --no-cache ca-certificates

# Copy the binary from the builder stage
COPY --from=builder /app/api-server .

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

# Expose the application port
EXPOSE 8080

# Environment variables with defaults (can be overridden)
ENV PORT=8080
ENV DATABASE_URL=""

# Run the binary
CMD ["./api-server"]
