# ==============================================================================
# Stage 1: Frontend Build (Runs natively on $BUILDPLATFORM — zero QEMU overhead)
# ==============================================================================
FROM --platform=$BUILDPLATFORM node:22-alpine AS frontend-builder
WORKDIR /app/frontend
COPY frontend/package*.json ./
RUN npm install --no-audit --no-fund
COPY frontend/ ./
RUN npm run build

# ==============================================================================
# Stage 2: Go Backend Build (Native Cross-Compile via TARGETOS / TARGETARCH)
# ==============================================================================
FROM --platform=$BUILDPLATFORM golang:1.23-alpine AS backend-builder
ARG TARGETOS=linux
ARG TARGETARCH=amd64
WORKDIR /app
RUN apk add --no-cache git ca-certificates
COPY go.mod ./
COPY cmd/ ./cmd/
COPY internal/ ./internal/
COPY migrations/ ./migrations/
# Copy compiled frontend SPA assets into cmd/server/dist for go:embed
COPY --from=frontend-builder /app/frontend/dist ./cmd/server/dist
RUN go mod tidy
RUN CGO_ENABLED=0 GOOS=${TARGETOS} GOARCH=${TARGETARCH} go build -ldflags="-s -w" -o /app/mindsift ./cmd/server

# ==============================================================================
# Stage 3: Minimal Production Runtime (< 35 MB)
# ==============================================================================
FROM alpine:3.21
RUN apk add --no-cache ca-certificates tzdata && \
    mkdir -p /data && \
    chown -R 1000:1000 /data

WORKDIR /app
COPY --from=backend-builder /app/mindsift /app/mindsift

ENV PORT=8080
ENV DATA_DIR=/data
VOLUME ["/data"]

EXPOSE 8080
USER 1000:1000
ENTRYPOINT ["/app/mindsift"]
