# Builder: pure Go, no CGO needed (external image API)
FROM golang:1.26.0-bookworm AS builder

RUN apt-get update && apt-get install -y --no-install-recommends \
    ca-certificates \
    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 not required)
RUN CGO_ENABLED=0 GOOS=linux go build -o main .

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

RUN apt-get update && apt-get install -y --no-install-recommends \
    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"]
