# ----- Build Stage -----
# Using a specific Ruby version (e.g., 3.3) for stability
ARG RUBY_VERSION=3.3.9
FROM ruby:$RUBY_VERSION as builder

# Install system dependencies needed for Ruby gems and asset building
RUN apt-get update -qq && apt-get install -y \
  build-essential \
  libpq-dev \
  libvips \
  nodejs \
  npm \
  git \
  curl \
  watchman \
  && rm -rf /var/lib/apt/lists/* \
  # For TailwindCSS, install the npm package instead of relying on the system executable
  # as there have been issues with architecture mismatches in containers
  && npm install -g tailwindcss

# Set the working directory inside the container
WORKDIR /usr/src/app

# Copy and install Ruby dependencies
COPY Gemfile Gemfile.lock ./
RUN bundle install

# Copy the rest of the application code
COPY . .

# Precompile assets for production using the installed Tailwind CLI
# This uses the installed 'tailwindcss' executable rather than the gem's wrapper
# RUN bundle exec rails assets:precompile

# ----- Production Stage -----
# Use a smaller Ruby image for the final production build
FROM ruby:$RUBY_VERSION-slim

# Install production system dependencies
RUN --mount=type=cache,target=/var/cache/apt \
  --mount=type=cache,target=/var/lib/apt,sharing=locked \
  --mount=type=tmpfs,target=/var/log \
  rm -f /etc/apt/apt.conf.d/docker-clean; \
  apt-get update -qq \
  && apt-get install -yq --no-install-recommends \
    build-essential \
    less \
    git \
    tdsodbc \
    freetds-dev \
    libvips \
    libpq-dev

ENV LANG=C.UTF-8 \
  BUNDLE_JOBS=4 \
  BUNDLE_RETRY=3

WORKDIR /usr/src/app

# Copy runtime Ruby dependencies and the precompiled assets from the builder stage
COPY --from=builder /usr/local/bundle /usr/local/bundle
COPY --from=builder /usr/src/app /usr/src/app
COPY --from=builder /usr/local/bin/watchman /usr/local/bin/watchman
COPY --from=builder /usr/local/bin/watchman-wait /usr/local/bin/watchman-wai

# The entrypoint script is a good practice for handling Rails server startup
ENTRYPOINT ["./bin/docker-entrypoint-development"]

# Expose the application port
EXPOSE 3002

# Set the default command to run the Rails server
CMD ["./bin/rails", "server"]
