# syntax = docker/dockerfile:1

# 1. Base Stage: Common dependencies
ARG RUBY_VERSION=3.4.8
FROM ruby:$RUBY_VERSION-slim as base

WORKDIR /rails
ENV RAILS_ENV="production" \
    BUNDLE_DEPLOYMENT="1" \
    BUNDLE_PATH="/usr/local/bundle" \
    BUNDLE_WITHOUT="development:test"
    # SUPERCRONIC_URL=https://github.com \
    # SUPERCRONIC=supercronic-linux-amd64 \
    # SUPERCRONIC_SHA1SUM=cd48d45327f3f3396734267468f707f43372c2fc

# Install base packages (libvips for Active Storage, curl for healthchecks)
RUN apt-get update -qq && \
    apt-get install --no-install-recommends -y \
    curl \
    git \
    libvips \
    freetds-bin \
    freetds-dev \
    libpq-dev \
    libyaml-dev \
    cron \
    libjemalloc2 \
    dos2unix && \
    rm -rf /var/lib/apt/lists /var/cache/apt/archives

# RUN curl -fsSLO "$SUPERCRONIC_URL" \
#  && echo "${SUPERCRONIC_SHA1SUM}  ${SUPERCRONIC}" | sha1sum -c - \
#  && chmod +x "$SUPERCRONIC" \
#  && mv "$SUPERCRONIC" /usr/local/bin/supercronic

# 2. Build Stage: Gems and Assets
FROM base as build

# Install packages needed to build gems and precompile assets
RUN apt-get update -qq && \
    apt-get install --no-install-recommends -y build-essential pkg-config less && \
    rm -rf /var/lib/apt/lists /var/cache/apt/archives

# Install application gems
RUN bundle config set --local frozen false
COPY Gemfile Gemfile.lock ./
RUN bundle install && \
    rm -rf ~/.bundle/ "${BUNDLE_PATH}"/ruby/*/cache "${BUNDLE_PATH}"/ruby/*/bundler/gems/*/.git

# Copy application code
COPY . .

# Precompile assets (Tailwind is triggered here via assets:precompile)
# SECRET_KEY_BASE_DUMMY allows precompilation without real secrets
RUN SECRET_KEY_BASE_DUMMY=1 ./bin/rails assets:precompile

# 3. Final Stage: Lean Runtime
FROM base

# Copy built artifacts: gems and precompiled assets
COPY --from=build /usr/local/bundle /usr/local/bundle
COPY --from=build /rails /rails

# Run as a non-privileged user for security
RUN useradd -ms /bin/bash rails
RUN chown -R rails:rails /rails
USER rails:rails

# Entrypoint prepares the database.
ENTRYPOINT ["/rails/bin/docker-entrypoint"]

# Start the server
EXPOSE 3002
CMD ["bundle", "exec", "puma", "-C", "config/puma.rb"]
