# Use official Deno runtime as base image
ARG DENO_VERSION=2.6.4
FROM denoland/deno:${DENO_VERSION}

# Set working directory
WORKDIR /app

# Copy dependency manifest first (better layer caching)
COPY deno.json deno.lock ./

# Copy source code
COPY src/ ./src/

# Cache dependencies by checking the main file
# This downloads and caches all imports
RUN deno cache src/main.ts

# Expose port (default: 8000)
EXPOSE 8000

# Create non-root user for security
RUN useradd -m -u 1001 denouser && \
    chown -R denouser:denouser /app

USER denouser

# Health check
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
  CMD deno eval "fetch('http://localhost:' + (Deno.env.get('PORT') || '8000') + '/health').then(r => r.ok ? Deno.exit(0) : Deno.exit(1))" || exit 1

# Run the application
CMD ["deno", "run", "--allow-net", "--allow-env", "src/main.ts"]
