# syntax=docker/dockerfile:1
# check=error=true

# --- Version Arguments ---
ARG RUBY_VERSION=3.2.4
ARG NODE_VERSION=22.16.0
ARG BUN_VERSION=1.3.9

# --- Stage 1: Grab Node.js Binaries ---
# We use the official image as a source for pre-compiled binaries
FROM docker.io/library/node:${NODE_VERSION}-slim AS node_source

# --- Stage 2: Base (Runtime Environment) ---
FROM docker.io/library/ruby:${RUBY_VERSION}-slim AS base

WORKDIR /rails

# Install runtime-only system packages
RUN --mount=type=cache,target=/var/cache/apt,sharing=locked \
    --mount=type=cache,target=/var/lib/apt,sharing=locked \
    apt-get update -qq && \
    apt-get install --no-install-recommends -y \
    curl libjemalloc2 libvips libpq-dev telnet imagemagick

# "Heist" Node.js and npm from the node_source stage
COPY --from=node_source /usr/local/bin/node /usr/local/bin/node
COPY --from=node_source /usr/local/lib/node_modules /usr/local/lib/node_modules

# Re-link npm and install Bun (Instantly available)
RUN ln -s /usr/local/lib/node_modules/npm/bin/npm-cli.js /usr/local/bin/npm && \
    npm install -g bun@${BUN_VERSION}

# Set production environment
ENV RAILS_ENV="production" \
    BUNDLE_DEPLOYMENT="1" \
    BUNDLE_PATH="/usr/local/bundle" \
    BUNDLE_WITHOUT="development" \
    BUNDLE_CACHE=true

# --- Stage 3: Build (Compilation & Assets) ---
FROM base AS build

# Install packages needed to build gems and node modules
RUN --mount=type=cache,target=/var/cache/apt,sharing=locked \
    --mount=type=cache,target=/var/lib/apt,sharing=locked \
    apt-get update -qq && \
    apt-get install --no-install-recommends -y \
    build-essential git libyaml-dev node-gyp pkg-config python-is-python3

# 1. Install Gems (Separate COPY for maximum caching)
COPY Gemfile Gemfile.lock ./
RUN --mount=type=cache,target=/usr/local/bundle/cache \
    bundle config set --local path "${BUNDLE_PATH}" && \
    bundle install && \
    bundle exec bootsnap precompile --gemfile

# 2. Install JavaScript dependencies (Separate COPY for maximum caching)
COPY package.json bun.lock ./
RUN bun install --frozen-lockfile

# 3. Copy application code
COPY . .

# 4. Precompile assets and bootsnap
RUN bundle exec bootsnap precompile app/ lib/ && \
    SECRET_KEY_BASE_DUMMY=1 ./bin/rails assets:precompile && \
    rm -rf node_modules tmp/cache

# --- Stage 4: Final Production Image ---
FROM base

# Copy built artifacts: gems and the app (with precompiled assets)
COPY --from=build "${BUNDLE_PATH}" "${BUNDLE_PATH}"
COPY --from=build /rails /rails

# Security: Run as non-root user
RUN groupadd --system --gid 1000 rails && \
    useradd rails --uid 1000 --gid 1000 --create-home --shell /bin/bash && \
    chown -R rails:rails db log tmp public

# Create versioninfo with build timestamp
RUN date +"%Y-%m-%d %H:%M:%S %Z" > public/versioninfo

USER 1000:1000

ENTRYPOINT ["/rails/bin/docker-entrypoint"]

EXPOSE 80
CMD ["./bin/thrust", "./bin/rails", "server"]
