# Stage 1: build the SPA. Build-time args mirror the (now removed) standalone
# oncall-web image (/oncall SPA base, /api/v1 API, Auth0 config baked in).
FROM node:20-bookworm AS web
WORKDIR /app

COPY apps/oncall-web/package*.json ./
RUN npm ci

COPY apps/oncall-web/ ./
COPY services/oncall/swagger.yaml /services/oncall/swagger.yaml

ARG REACT_APP_ONCALL_API_BASE=/api/v1
ARG REACT_APP_BASENAME=/oncall
ARG PUBLIC_URL=/oncall
# Auth0 config is env-specific and lives in apps/oncall-web/.env.<APP_ENV>
# (public values, committed). Vite picks the set via the build mode.
ARG APP_ENV=dev

ENV REACT_APP_ONCALL_API_BASE=${REACT_APP_ONCALL_API_BASE} \
    REACT_APP_BASENAME=${REACT_APP_BASENAME} \
    PUBLIC_URL=${PUBLIC_URL}

RUN npm run build -- --mode "${APP_ENV}"

# Stage 2: build the Go binary with the SPA embedded (-tags embedfrontend).
FROM golang:1.26.1-bookworm AS builder

ARG TARGETOS
ARG TARGETARCH

WORKDIR /src/services/oncall

# services/oncall/go.mod replaces github.com/tidbcloud/aisupport/packages/sdk-go/contracts
# with a local path (../../packages/sdk-go/contracts); it must exist in the build
# context before `go mod download` resolves it.
COPY packages/sdk-go/contracts /src/packages/sdk-go/contracts
COPY services/oncall/go.mod services/oncall/go.sum ./
RUN go mod download

COPY services/oncall ./
# Vite output dir is "build"; web/embed.go embeds ./web/build.
COPY --from=web /app/build ./web/build

RUN CGO_ENABLED=1 GOOS=${TARGETOS:-linux} GOARCH=${TARGETARCH:-amd64} \
    go build -tags embedfrontend -o /out/oncall ./main.go

# Stage 3: runtime.
FROM debian:bookworm-slim

RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates && rm -rf /var/lib/apt/lists/*

WORKDIR /app
COPY --from=builder /out/oncall /oncall
COPY infra/images/oncall/config.yaml /app/config.yaml

EXPOSE 8080
ENTRYPOINT ["/oncall"]
