FROM golang:1.24.2-alpine AS builder

WORKDIR /app

# Install necessary build tools and SQLite dependencies
RUN apk add --no-cache git make build-base sqlite-dev

# Copy go mod files first for better caching
COPY go.mod go.sum ./

# Download dependencies
RUN go mod download

# Copy the rest of the source code
COPY . .

# Build the application with SQLite support
RUN go build -tags 'sqlite' -o byop-engine .

# Create a minimal production image
FROM alpine:3.17

WORKDIR /app

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

# Create data directory for SQLite
RUN mkdir -p /app/data && chmod 755 /app/data

# Copy the binary from the builder stage
COPY --from=builder /app/byop-engine /app/byop-engine
COPY --from=builder /app/config.sample.yml /app/config.yaml

# Create a non-root user and switch to it
RUN adduser -D -u 1000 byopuser && \
    chown -R byopuser:byopuser /app
USER byopuser

# Expose the application port
EXPOSE 8080

# Run the application
CMD ["/app/byop-engine"]