# EncryptID Server Dockerfile
# Multi-stage build for optimized production image

# Build stage
FROM oven/bun:1.1 AS builder

WORKDIR /app

# Copy package files and encryptid-sdk (build context is parent dir)
COPY rspace-online/package.json rspace-online/bun.lockb* ./
COPY encryptid-sdk /encryptid-sdk/

# Rewrite file: dependency to absolute path for Docker build
RUN sed -i 's|"file:../encryptid-sdk"|"file:/encryptid-sdk"|' package.json

# Install dependencies (including postgres)
RUN bun install --frozen-lockfile || bun install

# Copy source
COPY rspace-online/src/encryptid ./src/encryptid
COPY rspace-online/public ./public
COPY rspace-online/tsconfig.json ./

# Build client-side modules for browser
RUN bun build ./src/encryptid/index.ts --outdir=./src/encryptid/dist --target=browser --minify

# Production stage
FROM oven/bun:1.1-slim

WORKDIR /app

# Copy from builder
COPY --from=builder /app/node_modules ./node_modules
COPY --from=builder /app/src/encryptid ./src/encryptid
COPY --from=builder /app/public ./public
COPY --from=builder /app/package.json ./

# Create non-root user
RUN addgroup --system --gid 1001 encryptid && \
    adduser --system --uid 1001 encryptid
USER encryptid

# Environment
ENV NODE_ENV=production
ENV PORT=3000

# Expose port
EXPOSE 3000

# Health check
HEALTHCHECK --interval=30s --timeout=10s --start-period=10s --retries=3 \
  CMD bun -e "fetch('http://localhost:3000/health').then(r => r.json()).then(d => process.exit(d.database ? 0 : 1)).catch(() => process.exit(1))"

# Start server
CMD ["bun", "run", "src/encryptid/server.ts"]
