# 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"

# 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

# 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 && \
    # mkdir -p /etc/apt/keyrings && \
    # curl -fsSL https://deb.nodesource.com/gpgkey/nodesource-repo.gpg.key | gpg --dearmor -o /etc/apt/keyrings/nodesource.gpg && \
    # echo "deb [signed-by=/etc/apt/keyrings/nodesource.gpg] https://deb.nodesource.com/node_20.x nodistro main" > /etc/apt/sources.list.d/nodesource.list && \
    # apt-get update && \
    # apt-get install nodejs -y && \
    rm -rf /var/lib/apt/lists /var/cache/apt/archives

# RUN apt-get install -y npm
# RUN npm install -g yarn

# 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 . .

RUN ./bin/rails stimulus:manifest:update
RUN ./bin/importmap pin .

# RUN bundle exec ./bin/rails rails_icons:sync
RUN ./bin/rails generate rails_icons:sync --libraries=lucide

# Precompile assets (Tailwind is triggered here via assets:precompile)
# SECRET_KEY_BASE_DUMMY allows precompilation without real secrets
# RUN bundle exec rails assets:clobber assets:precompile RAILS_ENV=production SECRET_KEY_BASE_DUMMY=1
RUN bundle exec rails assets:precompile RAILS_ENV=production SECRET_KEY_BASE_DUMMY=1

# 3. Final Stage: Lean Runtime
FROM base

# Copy built artifacts: gems and precompiled assets
# COPY --from=build /rails/public /rails/public
# COPY --from=build /rails/app/javascript /rails/app/javascript
# COPY --from=build /rails/config/importmap.rb /rails/config/importmap.rb
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"]
