# ── Build stage ──────────────────────────────────────────
FROM node:22-alpine AS builder

RUN corepack enable
WORKDIR /app

COPY . .

RUN pnpm install --frozen-lockfile

RUN pnpm --filter frontend build
RUN pnpm --filter proxy build

# Create a standalone production node_modules for frontend
RUN pnpm --filter frontend deploy --prod /deploy/frontend

# ── Runtime stage ────────────────────────────────────────
FROM node:22-alpine

RUN corepack enable && \
    apk add --no-cache nginx wget unzip ca-certificates

WORKDIR /app

# SvelteKit build becomes /app/frontend
COPY --from=builder /app/frontend/build ./frontend

# Production dependencies for the frontend
COPY --from=builder /deploy/frontend/node_modules ./frontend/node_modules
COPY --from=builder /deploy/frontend/package.json ./frontend/package.json

# Proxy is bundled into one JS file by esbuild
COPY --from=builder /app/proxy/dist ./proxy

COPY docker/nginx.conf /etc/nginx/http.d/default.conf
COPY docker/entrypoint.sh /entrypoint.sh

ARG POCKETBASE_VERSION=0.39.10

RUN wget -qO /tmp/pb.zip \
    "https://github.com/pocketbase/pocketbase/releases/download/v${POCKETBASE_VERSION}/pocketbase_${POCKETBASE_VERSION}_linux_amd64.zip" \
    && unzip -o /tmp/pb.zip -d /usr/local/bin/ \
    && rm /tmp/pb.zip

RUN chmod +x /entrypoint.sh /usr/local/bin/pocketbase

EXPOSE 3000 8090

CMD ["/entrypoint.sh"]
