# ── Stage 1: build ────────────────────────────────────────────────────────────
FROM golang:1.25-alpine AS builder

WORKDIR /src

# Install wget for downloading the Tailwind standalone CLI.
RUN apk add --no-cache wget

# Download Tailwind v3 standalone CLI for the target architecture.
# Supported: linux/amd64, linux/arm64.
RUN ARCH=$(uname -m) && \
    case "$ARCH" in \
      x86_64)  TW_ARCH=x64 ;; \
      aarch64) TW_ARCH=arm64 ;; \
      *)       echo "Unsupported arch: $ARCH" && exit 1 ;; \
    esac && \
    wget -qO /usr/local/bin/tailwindcss \
      "https://github.com/tailwindlabs/tailwindcss/releases/download/v3.4.17/tailwindcss-linux-${TW_ARCH}" && \
    chmod +x /usr/local/bin/tailwindcss

# Fetch Go module dependencies (cached separately from source).
COPY go.mod go.sum ./
RUN go mod download

# Copy the rest of the source.
COPY . .

# Compile Tailwind CSS and switch the template from CDN to the compiled file.
RUN tailwindcss -i web/templates/input.css -o web/static/tailwind.css --minify && \
    sed -i 's|<script src="https://cdn.tailwindcss.com"></script>|<link rel="stylesheet" href="/static/tailwind.css">|' \
        web/templates/layout.html

# Build the Go binary.
RUN CGO_ENABLED=0 GOOS=linux go build -o /out/qbank ./cmd/server

# ── Stage 2: run ──────────────────────────────────────────────────────────────
FROM gcr.io/distroless/static-debian12:nonroot

WORKDIR /app

COPY --from=builder /out/qbank          /app/qbank
COPY --from=builder /src/web/templates  /app/web/templates
COPY --from=builder /src/web/static     /app/web/static

EXPOSE 8080

USER nonroot:nonroot

ENTRYPOINT ["/app/qbank"]
