# Dockerfile for running super-sync-server in test mode
# Used for E2E tests that need a real sync server
#
# Build from repo root (to include workspace deps):
#   docker build -f packages/super-sync-server/Dockerfile.test .
#
# Run:
#   docker run -p 1900:1900 supersync-test

FROM node:22-alpine

WORKDIR /app

# Install required system dependencies for Prisma
RUN apk add --no-cache openssl libc6-compat

# Copy package files for workspace setup
COPY package.json package-lock.json ./
COPY packages/sync-core/package.json ./packages/sync-core/
COPY packages/shared-schema/package.json ./packages/shared-schema/
COPY packages/super-sync-server/package.json ./packages/super-sync-server/

# Install dependencies (ignore scripts to skip husky/prepare from root)
# Using npm install instead of npm ci due to workspace lock file sync issues
RUN npm install --workspace=packages/sync-core --workspace=packages/shared-schema --workspace=packages/super-sync-server --ignore-scripts

# Copy source files
COPY packages/sync-core/ ./packages/sync-core/
COPY packages/shared-schema/ ./packages/shared-schema/
COPY packages/super-sync-server/ ./packages/super-sync-server/

# Build sync-core first, then shared-schema
WORKDIR /app/packages/sync-core
RUN npm run build

WORKDIR /app/packages/shared-schema
RUN npm run build

# Build super-sync-server
WORKDIR /app/packages/super-sync-server
# Generate Prisma Client
RUN npx prisma generate
# Clean dist folder to remove any stale files that might conflict
RUN rm -rf dist && npm run build

# Copy public files to dist
RUN cp -r public dist/

EXPOSE 1900

# Run in test mode
ENV PORT=1900
ENV TEST_MODE=true
ENV TEST_MODE_CONFIRM=yes-i-understand-the-risks
ENV CORS_ORIGINS=*
ENV JWT_SECRET=e2e-test-secret-minimum-32-chars-long-for-security

# Push schema to DB and start server.
# Retry `prisma db push` for up to ~30s on transient connection failures
# (postgres can briefly bounce during first-run initdb even after the db's
# healthcheck passes). Without this, the container exits on first P1001
# and depends on docker's restart policy to recover, which can't be relied
# on across compose invocations.
#
# Exec form is required: shell form would wrap this in an extra `/bin/sh -c`,
# and the outer shell would expand `$(seq 1 15)` into a multi-line string that
# busybox's ash refuses to parse inside `for ... in` ("expected do").
#
# `exec node ...` on success replaces the shell with node so the loop cannot
# fall through. If all 15 attempts fail we exit 1 instead of starting the
# server against an unmigrated DB (which would surface as confusing Prisma
# errors at request time rather than a clean container failure).
CMD ["sh", "-c", "for i in $(seq 1 15); do npx prisma db push && exec node dist/src/index.js; echo \"prisma db push failed (attempt $i/15), retrying in 2s...\"; sleep 2; done; echo \"prisma db push failed after 15 attempts, giving up\" >&2; exit 1"]
