# frozen_string_literal: true

class TopicsBulkAction
  attr_reader :errors

  def initialize(user, topic_ids, operation, options = {})
    @user = user
    @topic_ids = topic_ids
    @operation = operation
    @changed_ids = []
    @errors = Hash.new(0)
    @restricted_tag_errors = Hash.new(0)
    @options = options
  end

  def tag_category_errors
    return [] if @restricted_tag_errors.empty?

    category_names =
      Category.where(id: @restricted_tag_errors.keys.map(&:first).uniq).pluck(:id, :name).to_h

    @restricted_tag_errors.map do |(category_id, tag_names), count|
      {
        category_id: category_id,
        category_name: category_names[category_id],
        tag_names: tag_names,
        count: count,
      }
    end
  end

  def self.operations
    @operations ||= %w[
      change_category
      close
      archive
      change_notification_level
      destroy_post_timing
      dismiss_posts
      delete
      unlist
      archive_messages
      move_messages_to_inbox
      change_tags
      append_tags
      remove_tags
      manage_tags
      relist
      dismiss_topics
      reset_bump_dates
      pin
      unpin
      convert_to_public_topic
      convert_to_private_message
      enable_nested_view
      disable_nested_view
    ]
  end

  def self.register_operation(name, &block)
    operations << name
    define_method(name, &block)
  end

  def perform!
    if TopicsBulkAction.operations.exclude?(@operation[:type])
      raise Discourse::InvalidParameters.new(:operation)
    end

    # careful these are private methods, we need send
    send(@operation[:type])

    if @errors.present?
      error_details = @errors.map { |msg, count| "- #{msg} (#{count} topics)" }.join("\n")
      Rails.logger.warn(
        "Bulk '#{@operation[:type]}' by @#{@user.username} (id=#{@user.id}) failed for #{@errors.values.sum} topics:\n#{error_details}",
      )
    end

    @changed_ids.sort
  end

  private

  def find_group
    return unless @options[:group]

    group = Group.where("name ilike ?", @options[:group]).first
    raise Discourse::InvalidParameters.new(:group) unless group
    unless group.group_users.where(user_id: @user.id).exists?
      raise Discourse::InvalidParameters.new(:group)
    end
    group
  end

  def move_messages_to_inbox
    group = find_group
    topics.each do |t|
      if guardian.can_see?(t) && t.private_message?
        next if group && !t.topic_allowed_groups.exists?(group_id: group.id)

        if group
          GroupArchivedMessage.move_to_inbox!(group.id, t, acting_user_id: @user.id)
        else
          UserArchivedMessage.move_to_inbox!(@user.id, t)
        end
        @changed_ids << t.id
      end
    end
  end

  def archive_messages
    group = find_group
    topics.each do |t|
      if guardian.can_see?(t) && t.private_message?
        next if group && !t.topic_allowed_groups.exists?(group_id: group.id)

        if group
          GroupArchivedMessage.archive!(group.id, t, acting_user_id: @user.id)
        else
          UserArchivedMessage.archive!(@user.id, t)
        end
        @changed_ids << t.id
      end
    end
  end

  def dismiss_posts
    highest_number_source_column =
      @user.whisperer? ? "highest_staff_post_number" : "highest_post_number"

    sql = <<~SQL
      UPDATE topic_users tu
      SET last_read_post_number = t.#{highest_number_source_column}
      FROM topics t
      WHERE t.id = tu.topic_id AND tu.user_id = :user_id AND t.id IN (:topic_ids)
    SQL

    DB.exec(sql, user_id: @user.id, topic_ids: @topic_ids)
    TopicTrackingState.publish_dismiss_new_posts(@user.id, topic_ids: @topic_ids.sort)

    @changed_ids.concat @topic_ids
  end

  def dismiss_topics
    ids =
      Topic
        .where(id: @topic_ids)
        .joins(
          "LEFT JOIN topic_users ON topic_users.topic_id = topics.id AND topic_users.user_id = #{@user.id}",
        )
        .where("topics.created_at >= ?", dismiss_topics_since_date)
        .where("topic_users.last_read_post_number IS NULL")
        .order("topics.created_at DESC")
        .limit(SiteSetting.max_new_topics)
        .filter { |t| guardian.can_see?(t) }
        .map(&:id)

    if ids.present?
      now = Time.zone.now
      rows = ids.map { |id| { topic_id: id, user_id: @user.id, created_at: now } }
      DismissedTopicUser.insert_all(rows)
      TopicTrackingState.publish_dismiss_new(@user.id, topic_ids: ids.sort)
    end

    @changed_ids = ids
  end

  def destroy_post_timing
    topics.each do |t|
      next unless guardian.can_see?(t)

      PostTiming.destroy_last_for(@user, topic: t)
      @changed_ids << t.id
    end
  end

  def change_category
    category_id = @operation[:category_id]
    updatable_topics = topics.where.not(category_id: category_id)

    # mirrors the PostRevisor gate, which skips the check when moving to uncategorized
    if category_id.to_i > 0 && !guardian.can_move_topic_to_category?(category_id)
      @errors[I18n.t("category.errors.move_topic_to_category_disallowed")] += updatable_topics.count
      return
    end

    updatable_topics.each do |t|
      next unless guardian.can_edit?(t) && t.first_post

      changes = { category_id: category_id }
      if t.first_post.revise(@user, changes, bulk_revision_opts)
        @changed_ids << t.id
      else
        t.errors.full_messages.each { |msg| @errors[msg] += 1 }
      end
    end
  end

  def convert_to_public_topic
    bulk_convert(from_pm: true) { |c| c.convert_to_public_topic(@operation[:category_id]) }
  end

  def convert_to_private_message
    bulk_convert(from_pm: false, &:convert_to_private_message)
  end

  def bulk_convert(from_pm:)
    silent = @operation.fetch(:silent, true)

    topics.each do |t|
      next if t.private_message? != from_pm
      next unless guardian.can_convert_topic?(t)

      yield TopicConverter.new(t, @user, silent: silent)

      if t.errors.any?
        t.errors.full_messages.each { |msg| @errors[msg] += 1 }
      elsif t.reload.private_message? != from_pm
        @changed_ids << t.id
      end
    end
  end

  def change_notification_level
    notification_level_id = @operation[:notification_level_id]

    raise Discourse::InvalidParameters.new(:notification_level_id) if notification_level_id.blank?

    topics.each do |t|
      if guardian.can_see?(t)
        TopicUser.change(@user, t.id, notification_level: notification_level_id.to_i)
        @changed_ids << t.id
      end
    end
  end

  def close
    topics.each do |t|
      if guardian.can_moderate?(t)
        t.update_status("closed", true, @user, { message: @operation[:message] })
        @changed_ids << t.id
      end
    end
  end

  def unlist
    topics.each do |t|
      if guardian.can_moderate?(t)
        t.update_status(
          "visible",
          false,
          @user,
          { visibility_reason_id: Topic.visibility_reasons[:bulk_action] },
        )
        @changed_ids << t.id
      end
    end
  end

  def relist
    topics.each do |t|
      if guardian.can_moderate?(t)
        t.update_status(
          "visible",
          true,
          @user,
          { visibility_reason_id: Topic.visibility_reasons[:bulk_action] },
        )
        @changed_ids << t.id
      end
    end
  end

  def reset_bump_dates
    if guardian.can_update_bumped_at?
      topics.each do |t|
        next unless guardian.can_see?(t)

        t.reset_bumped_at
        @changed_ids << t.id
      end
    end
  end

  def pin
    status = @operation[:pinned_globally] ? "pinned_globally" : "pinned"
    topics.each do |t|
      if guardian.can_moderate?(t)
        t.update_status(status, true, @user, until: @operation[:pinned_until])
        @changed_ids << t.id
      end
    end
  end

  def unpin
    topics.each do |t|
      if guardian.can_moderate?(t) && t.pinned_at
        status = t.pinned_globally ? "pinned_globally" : "pinned"
        t.update_status(status, false, @user)
        @changed_ids << t.id
      end
    end
  end

  def archive
    topics.each do |t|
      if guardian.can_moderate?(t)
        t.update_status("archived", true, @user)
        @changed_ids << t.id
      end
    end
  end

  def delete
    topics.each do |t|
      next if !guardian.can_delete?(t)

      post = t.ordered_posts.with_deleted.first
      next if !post

      PostDestroyer.new(@user, post).destroy
      @changed_ids << t.id
    end
  end

  def enable_nested_view
    toggle_nested_view(enabled: true)
  end

  def disable_nested_view
    toggle_nested_view(enabled: false)
  end

  def toggle_nested_view(enabled:)
    return unless SiteSetting.nested_replies_enabled
    return if SiteSetting.nested_replies_default

    topics.each do |t|
      next if t.private_message?

      result = NestedTopic::Toggle.call(guardian: guardian, params: { topic_id: t.id, enabled: })
      @changed_ids << t.id if result.success?
    end
  end

  def change_tags
    tags = resolve_tag_names || []
    topics_with_tags.each { |t| apply_tag_revision(t, tags) }
  end

  def append_tags
    tags = resolve_tag_names || []
    return if tags.blank?

    topics_with_tags.each do |t|
      merged = t.tags.map(&:name) | tags
      apply_tag_revision(t, merged)
    end
  end

  def remove_tags
    topics_with_tags.each { |t| apply_tag_revision(t, []) }
  end

  def manage_tags
    add_ids = (@operation[:add_tag_ids] || []).map(&:to_i)
    remove_ids = (@operation[:remove_tag_ids] || []).map(&:to_i)
    replace_pairs =
      (@operation[:replace_tags] || []).map { |e| [e[:from_tag_id].to_i, e[:to_tag_id].to_i] }

    valid_ids = Tag.where(id: (add_ids + remove_ids + replace_pairs).flatten).pluck(:id)
    add_ids &= valid_ids
    remove_ids &= valid_ids
    replace_map =
      replace_pairs.each_with_object({}) do |(from_id, to_id), map|
        map[from_id] ||= to_id if valid_ids.include?(from_id) && valid_ids.include?(to_id)
      end

    topics_with_tags.each do |t|
      current = t.tags.map(&:id)
      base = @operation[:remove_all_tags] ? [] : current - remove_ids
      final = (base | add_ids).map { |id| replace_map[id] || id }.uniq

      next if final.sort == current.sort

      apply_tag_revision(t, Tag.where(id: final).pluck(:name))
    end
  end

  def apply_tag_revision(topic, tag_names)
    unless guardian.can_edit_tags?(topic)
      @errors[I18n.t("tags.user_not_permitted")] += 1
      return false
    end
    return false unless topic.first_post

    if topic.first_post.revise(@user, { tags: tag_names }, bulk_revision_opts)
      @changed_ids << topic.id
      true
    else
      not_allowed =
        DiscourseTagging.tag_names_not_allowed_in_category(
          topic.category,
          tag_names,
          restricted_to: restricted_category_ids_for(tag_names),
        )
      if topic.category && not_allowed.present?
        @restricted_tag_errors[[topic.category_id, not_allowed.sort]] += 1
      else
        topic.errors.full_messages.each { |msg| @errors[msg] += 1 }
      end
      false
    end
  end

  def restricted_category_ids_for(tag_names)
    @restricted_tag_cache ||= {}
    uncached = tag_names - @restricted_tag_cache.keys
    if uncached.present?
      found = DiscourseTagging.restricted_category_ids_by_tag_name(uncached)
      uncached.each { |name| @restricted_tag_cache[name] = found.key?(name) ? found[name] : nil }
    end
    @restricted_tag_cache.slice(*tag_names).compact
  end

  def resolve_tag_names
    if @operation[:tag_ids].present?
      Tag.where(id: @operation[:tag_ids]).pluck(:name)
    elsif @operation[:tags].present?
      Discourse.deprecate(
        "the tags param for bulk actions is deprecated, use tag_ids instead",
        since: "2026.01",
        drop_from: "2026.07",
      )
      @operation[:tags]
    end
  end

  def bulk_revision_opts
    @bulk_revision_opts ||= {
      bypass_bump: true,
      validate_post: false,
      bypass_rate_limiter: true,
      silent: @operation.fetch(:silent, true),
    }
  end

  def guardian
    @guardian ||= Guardian.new(@user)
  end

  def topics
    @topics ||= Topic.where(id: @topic_ids).includes(:category)
  end

  def topics_with_tags
    @topics_with_tags ||= topics.includes(:first_post, :tags, :category)
  end

  def dismiss_topics_since_date
    new_topic_duration_minutes =
      @user.user_option&.new_topic_duration_minutes ||
        SiteSetting.default_other_new_topic_duration_minutes
    setting_date =
      case new_topic_duration_minutes
      when User::NewTopicDuration::LAST_VISIT
        @user.previous_visit_at || @user.created_at
      when User::NewTopicDuration::ALWAYS
        @user.created_at
      else
        new_topic_duration_minutes.minutes.ago
      end
    [setting_date, @user.created_at, Time.at(SiteSetting.min_new_topics_time).to_datetime].max
  end
end
