# ─── Stage 1: Build frontend ───
FROM node:22-alpine AS frontend-builder
WORKDIR /frontend
COPY frontend/package.json frontend/package-lock.json ./
RUN npm ci --production=false
COPY frontend/ .
RUN npm run build

# ─── Stage 2: Build backend ───
FROM golang:1.26-alpine AS backend-builder
RUN apk add --no-cache git ca-certificates
WORKDIR /app
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 GOOS=linux go build -ldflags="-s -w" -o /sub-store .

# ─── Stage 3: Runtime ───
FROM alpine:3.21
RUN apk add --no-cache ca-certificates tzdata && \
    wget -qO /tmp/sing-box.tar.gz "https://github.com/SagerNet/sing-box/releases/download/v1.11.4/sing-box-1.11.4-linux-amd64.tar.gz" && \
    tar xzf /tmp/sing-box.tar.gz -C /tmp && \
    mv /tmp/sing-box-*/sing-box /usr/local/bin/sing-box && \
    chmod +x /usr/local/bin/sing-box && \
    rm -rf /tmp/sing-box*
WORKDIR /app
COPY --from=backend-builder /sub-store /app/sub-store
COPY --from=frontend-builder /frontend/dist /app/frontend/dist
COPY config/config.example.yaml /app/config/config.example.yaml

RUN mkdir -p /app/data

ENV TZ=Asia/Shanghai
ENV SUB_STORE_CONFIG=/app/config/config.yaml
ENV SUB_STORE_FRONTEND_DIR=/app/frontend/dist

EXPOSE 3000

ENTRYPOINT ["/app/sub-store"]
CMD ["serve", "-c", "/app/config/config.yaml"]
