# ==============================================================================
# Stage 1: Build the Go Binaries
# ==============================================================================
FROM golang:1.26-alpine AS builder

WORKDIR /app

# Install git and certificates
RUN apk add --no-cache git ca-certificates tzdata

# Download dependencies
COPY go.mod go.sum ./
RUN go mod download

# Copy backend source code
COPY . .

# Build pure-Go static binaries
RUN CGO_ENABLED=0 GOOS=linux go build -ldflags="-w -s" -o /bin/api ./cmd/api && \
    CGO_ENABLED=0 GOOS=linux go build -ldflags="-w -s" -o /bin/seed ./cmd/seed && \
    CGO_ENABLED=0 GOOS=linux go build -ldflags="-w -s" -o /bin/export-content ./cmd/export-content

# ==============================================================================
# Stage 2: Minimal Runtime Image
# ==============================================================================
FROM alpine:3.20

WORKDIR /app

# Install ca-certificates and sqlite cli for maintenance
RUN apk add --no-cache ca-certificates tzdata sqlite curl && \
    addgroup -S appgroup && adduser -S appuser -G appgroup

# Create persistent database storage directory
RUN mkdir -p /app/data && chown -R appuser:appgroup /app/data

# Copy built binaries from builder
COPY --from=builder /bin/api /app/bin/api
COPY --from=builder /bin/seed /app/bin/seed
COPY --from=builder /bin/export-content /app/bin/export-content

# Copy seed data
COPY --from=builder /app/seed /app/seed

# Copy environment template
COPY --from=builder /app/.env.example /app/.env

# Set environment defaults for container
ENV HOST=0.0.0.0 \
    PORT=8080 \
    DB_PATH=/app/data/anl.db \
    GIN_MODE=release \
    CORS_ALLOW_ORIGINS=* \
    AUTO_MIGRATE=true

EXPOSE 8080

USER appuser

HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
  CMD curl -f http://localhost:8080/api/v1/health || exit 1

ENTRYPOINT ["/app/bin/api"]
