# Build stage
FROM golang:1.21-alpine AS builder

WORKDIR /app

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

# Copy all source files
COPY . .

# Remove any outdated/corrupted go.sum and let Go regenerate a pristine, valid one
RUN rm -f go.sum && go mod tidy && go mod download

# Build the application
RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o blogging-cms .

# Runtime stage
FROM alpine:latest

WORKDIR /app

# Receive PORT build arg from Coolify / Docker Compose (defaults to 8080 if unset)
ARG PORT=8080
# Set PORT environment variable for runtime, HEALTHCHECK, and Go application
ENV PORT=${PORT}

# Install runtime dependencies
RUN apk add --no-cache ca-certificates tzdata

# Copy built application
COPY --from=builder /app/blogging-cms .

# Copy templates and static files
COPY templates ./templates
COPY static ./static

# Create non-root user
RUN addgroup -g 1000 appuser && \
    adduser -D -u 1000 -G appuser appuser && \
    chown -R appuser:appuser /app

USER appuser

EXPOSE ${PORT}

HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
    CMD wget --quiet --tries=1 --spider http://localhost:${PORT}/ || exit 1

CMD ["./blogging-cms"]