class DisconnectionTimeoutJob
  include Sidekiq::Job

  def perform(session_id)
    session = StreamSession.find_by(id: session_id)
    return unless session&.reconnecting?

    session.finish! if session.may_finish?
    session.update!(timeout_job_id: nil)
    session.stream_events.create!(
      event_type: "error",
      metadata: { reason: "reconnect_timeout" },
      occurred_at: Time.current
    )
    SessionChannel.broadcast_message(session, {
      type: "stream_event",
      event: "timeout_ended",
      message: "Session ended after reconnect timeout"
    })
    Sessions::Stop.new(session).call
  end
end
