# ─── 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/mihomo.gz "https://github.com/MetaCubeX/mihomo/releases/download/v1.19.29/mihomo-linux-amd64-v1.19.29.gz" && \
    gunzip /tmp/mihomo.gz && \
    mv /tmp/mihomo /usr/local/bin/mihomo && \
    chmod +x /usr/local/bin/mihomo && \
    rm -rf /tmp/mihomo*
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"]
