class TheatreSkipFinalizer
  def self.call(theatre:, user:)
    new(theatre:, user:).call
  end

  def initialize(theatre:, user:)
    @theatre = theatre
    @user = user
  end

  def call
    return unless theatre.current_post

    post = theatre.current_post
    voters = TheatreSkipVote.where(theatre:, post:).includes(:user).map(&:user)
    return if voters.empty?

    event = TheatreSkipEvent.create!(
        theatre:,
        post:,
        skipped_by_user: user,
        programme_position: theatre.programmes.maximum(:position))

    voters.uniq(&:id).each do |voter|
      TheatreSkipEventVoter.create!(theatre_skip_event: event, user: voter)
    end

    post.tags.find_each do |tag|
      TheatreSkipEventTag.create!(theatre_skip_event: event, tag:)
    end

    TheatreSkipVote.where(theatre:, post:).delete_all

    event
  end

  private

  attr_reader :theatre, :user
end
