# typed: strict
class Domain::Fa::Job::BrowsePageJob < Domain::Fa::Job::Base
  queue_as :fa_browse_page
  MAX_PAGE_NUMBER = T.let(Rails.env.development? ? 2 : 150, Integer)

  sig { params(args: T.untyped).void }
  def initialize(*args)
    super(*T.unsafe(args))
    @page_number = T.let(1, Integer)
    @total_num_new_posts_seen = T.let(0, Integer)
    @total_num_posts_seen = T.let(0, Integer)
  end

  sig { override.params(args: T::Hash[Symbol, T.untyped]).returns(T.untyped) }
  def perform(args)
    while true
      break unless scan_browse_page

      if @page_number > MAX_PAGE_NUMBER
        logger.warn(
          format_tags(
            make_tag("page_number", @page_number),
            make_tag("max_page_number", MAX_PAGE_NUMBER),
            "exceeded max page number",
          ),
        )
        break
      end
      @page_number += 1
    end

    logger.info(
      format_tags(
        make_tag("total new posts", @total_num_new_posts_seen),
        make_tag("total seen posts", @total_num_posts_seen),
        make_tag("pages", @page_number),
        "finished",
      ),
    )
  end

  private

  sig { returns(T::Boolean) }
  def scan_browse_page
    if @page_number == 1
      url = "https://www.furaffinity.net/browse/"
    else
      url = "https://www.furaffinity.net/browse/#{@page_number}/"
    end

    response = http_client.get(url)

    if response.status_code != 200
      fatal_error(
        "non 200 response for /browse: #{response.status_code.to_s.underline}",
      )
    end

    page = Domain::Fa::Parser::Page.from_log_entry(response.log_entry)
    listing_page_stats =
      update_and_enqueue_posts_from_listings_page(
        ListingPageType::BrowsePage.new(page_number: @page_number),
        page_parser: page,
      )

    enqueue_jobs_from_found_links(response.log_entry)

    @total_num_new_posts_seen += listing_page_stats.new_posts.count
    @total_num_posts_seen += listing_page_stats.all_posts.count
    listing_page_stats.new_posts.count > 0
  end
end
