# Use standard Bun image for debugging (switch back to alpine later)
FROM oven/bun:debian as base

# Install basic debugging tools
RUN apt-get update && apt-get install -y sqlite3
WORKDIR /app
# Default data dir for SQLite; can be overridden by DB_PATH at runtime (DB_PATH has priority)
ENV DATA_DIR=/app/data

# Create data directory with proper permissions
RUN mkdir -p /app/data && chown -R bun:bun /app/data

# Install bot dependencies first (better layer caching)
COPY package.json bun.lock ./
RUN bun install

# Prepare and install web dependencies
COPY apps/web/package.json apps/web/
WORKDIR /app/apps/web
# No instalar optionalDependencies (better-sqlite3) en build de producción
RUN bun install --no-optional

# Copy sources
WORKDIR /app
COPY src/ ./src/
COPY index.ts ./
COPY apps/web/ /app/apps/web/
COPY proxy.ts ./

# Build the web app
WORKDIR /app/apps/web
RUN bunx svelte-kit sync && bun run build

# Return to root workdir
WORKDIR /app

# More forgiving health check during debugging (router en 3000)
HEALTHCHECK --start-period=30s --interval=30s --timeout=3s --retries=3 \
	CMD curl -f http://localhost:3000/health || exit 0

# Expose router port
EXPOSE 3000
# Declare volume for persistent data by default
VOLUME ["/app/data"]

# Make script executable
COPY startup.sh ./
RUN chmod +x startup.sh

# Start via wrapper script
CMD ["./startup.sh"]
