# Builder: use Debian-based Go image so we can install libvips with AVIF support
FROM golang:1.25.7-bookworm AS builder

# Install build dependencies including libvips dev packages and AVIF/heif libs
RUN apt-get update && apt-get install -y --no-install-recommends \
    build-essential \
    pkg-config \
    gcc \
    libc6-dev \
    libvips-dev \
    libvips-tools \
    libheif-dev \
    libavif-dev \
    libjpeg-dev \
    libpng-dev \
    libwebp-dev \
    ca-certificates \
    make \
    git \
    && rm -rf /var/lib/apt/lists/*

# Set working directory
WORKDIR /app

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

# Download dependencies
RUN go mod download

# Copy the source code
COPY . .

# Build the application (CGO_ENABLED=1 required for bimg)
RUN CGO_ENABLED=1 GOOS=linux go build -o main .

# --- Final Stage ---
FROM debian:bookworm-slim

# Install runtime dependencies: libvips and supporting libs (with AVIF support)
RUN apt-get update && apt-get install -y --no-install-recommends \
    libvips \
    libheif-dev \
    libavif-dev \
    ca-certificates \
    tzdata \
    && rm -rf /var/lib/apt/lists/*

WORKDIR /app

# Copy the binary and assets from the builder stage
COPY --from=builder /app/main .
COPY --from=builder /app/views ./views
COPY --from=builder /app/public ./public

# Create uploads directory
RUN mkdir -p uploads && chown -R 1000:1000 /app/uploads

# Add entrypoint and make executable
COPY docker-entrypoint.sh /usr/local/bin/docker-entrypoint.sh
RUN chmod +x /usr/local/bin/docker-entrypoint.sh

# Create a non-root user for running the app
RUN groupadd -g 1000 appuser && useradd -u 1000 -g appuser -s /bin/sh -m appuser

# Expose port
EXPOSE 8080

ENTRYPOINT ["/usr/local/bin/docker-entrypoint.sh"]
USER appuser
CMD ["./main"]
