module Sessions
  class Pause
    def initialize(session)
      @session = session
    end

    def call
      cancel_timeout_job
      @session.pause! if @session.may_pause?
      ensure_slate_on_path
      log_event("paused")
      SessionChannel.broadcast_message(@session, { type: "command", action: "pause_stream" })
      SessionChannel.broadcast_message(@session, { type: "stream_event", event: "paused" })
      @session
    end

    private

    def cancel_timeout_job
      return if @session.timeout_job_id.blank?

      Sidekiq::ScheduledSet.new.find_job(@session.timeout_job_id)&.delete
      @session.update!(timeout_job_id: nil)
    end

    def ensure_slate_on_path
      Mediamtx::Client.new.patch_path(@session)
    rescue Mediamtx::Client::Error => e
      Rails.logger.warn("[Sessions::Pause] slate path patch failed: #{e.message}")
    end

    def log_event(type)
      @session.stream_events.create!(event_type: type, occurred_at: Time.current, metadata: {})
    end
  end
end
