# Build stage
FROM golang:1.21-alpine AS builder

RUN apk add --no-cache gcc musl-dev sqlite-dev

WORKDIR /build

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

# Copy source code (not .env, .git, etc — handled by .dockerignore)
COPY . .
RUN CGO_ENABLED=1 GOOS=linux go build -o db-monitor -ldflags="-s -w" .

# Runtime stage
FROM alpine:3.19

RUN apk add --no-cache ca-certificates sqlite-libs tzdata

# Create non-root user
RUN addgroup --system nonroot && adduser --system --ingroup nonroot nonroot

WORKDIR /app

COPY --from=builder /build/db-monitor .
COPY --from=builder /build/web ./web

RUN mkdir -p /data && chown -R nonroot:nonroot /app /data

ENV DB_MONITOR_PORT=9432
ENV DB_MONITOR_INTERVAL=15
ENV DB_MONITOR_SQLITE_PATH=/data/db-monitor.db

EXPOSE 9432
VOLUME ["/data"]

USER nonroot

HEALTHCHECK --interval=30s --timeout=5s --retries=3 \
    CMD wget -q --spider http://localhost:9432/api/status || exit 1

ENTRYPOINT ["./db-monitor"]
