# Multi-stage Docker build for TankStopp
# Stage 1: Build stage
FROM golang:1.24-alpine AS builder

# Install build dependencies
RUN apk add --no-cache git gcc musl-dev sqlite-dev

# Set working directory
WORKDIR /app

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

# Install templ for template generation
RUN go install github.com/a-h/templ/cmd/templ@latest

# Copy source code
COPY . .

# Generate templates
RUN templ generate

# Build the application
RUN CGO_ENABLED=1 GOOS=linux go build -a -installsuffix cgo -ldflags '-extldflags "-static"' -o tankstopp ./cmd/main.go

# Stage 2: Runtime stage
FROM alpine:3.18

# Install runtime dependencies
RUN apk add --no-cache \
    ca-certificates \
    sqlite \
    tzdata \
    && rm -rf /var/cache/apk/*

# Create non-root user
RUN addgroup -g 1001 -S tankstopp && \
    adduser -u 1001 -S tankstopp -G tankstopp

# Set working directory
WORKDIR /app

# Create necessary directories
RUN mkdir -p /app/data /app/logs /app/static && \
    chown -R tankstopp:tankstopp /app

# Copy binary from builder stage
COPY --from=builder /app/tankstopp /app/tankstopp
RUN chmod +x /app/tankstopp

# Copy static files
COPY --chown=tankstopp:tankstopp static/ /app/static/

# Copy configuration files
COPY --chown=tankstopp:tankstopp config*.yaml /app/

# Switch to non-root user
USER tankstopp

# Expose port
EXPOSE 8080

# Set environment variables
ENV TANKSTOPP_APP_ENVIRONMENT=production
ENV TANKSTOPP_SERVER_HOST=0.0.0.0
ENV TANKSTOPP_SERVER_PORT=8080
ENV TANKSTOPP_DATABASE_PATH=/app/data/fuel_stops.db
ENV TANKSTOPP_LOGGING_OUTPUT=stdout
ENV TANKSTOPP_LOGGING_LEVEL=info

# Add health check
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
    CMD wget --no-verbose --tries=1 --spider http://localhost:8080/ || exit 1

# Create volume for data persistence
VOLUME ["/app/data"]

# Start the application
CMD ["./tankstopp"]
